Skip to content

Instantly share code, notes, and snippets.

@zhanghongquan
Created January 9, 2020 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhanghongquan/0f09f545460739f1b59060affa95ae50 to your computer and use it in GitHub Desktop.
Save zhanghongquan/0f09f545460739f1b59060affa95ae50 to your computer and use it in GitHub Desktop.
measure context switch time
#include <chrono>
#include <condition_variable>
#include <functional>
#include <iostream>
#include <thread>
#include <vector>
class FlipFlop {
public:
inline void notify() {
std::unique_lock<std::mutex> gd(mLock);
mbNotified = true;
mCv.notify_one();
}
inline void wait() {
std::unique_lock<std::mutex> gd(mLock);
if(!mbNotified) {
mCv.wait(gd);
}
}
inline void connect(FlipFlop* other) {
mOther = other;
}
void runAsLeader(int count) {
for(int loop = 0; loop < count; loop++) {
mOther->notify();
wait();
}
}
void runAsFollower(int count) {
for(int loop = 0; loop < count; loop++) {
wait();
mOther->notify();
}
}
private:
FlipFlop* mOther;
std::condition_variable mCv;
std::mutex mLock;
volatile bool mbNotified = false;
};
int main() {
std::vector<std::thread*> threads;
std::vector<FlipFlop*> runners;
int runCount = 50000000;
auto time_start = std::chrono::steady_clock::now();
for(int count = 0 ; count < 1; count++) {
auto *leader = new FlipFlop();
auto *follower = new FlipFlop();
runners.push_back(leader);
runners.push_back(follower);
leader->connect(follower);
follower->connect(leader);
auto threadLeader = new std::thread(std::bind(&FlipFlop::runAsLeader, leader, runCount));
auto threadFollower = new std::thread(std::bind(&FlipFlop::runAsFollower, follower, runCount));
threads.push_back(threadLeader);
threads.push_back(threadFollower);
}
for(auto& t: threads) {
t->join();
delete t;
}
auto time_end = std::chrono::steady_clock::now();
auto diff = std::chrono::duration_cast<std::chrono::microseconds>(time_end - time_start);
for(auto& r : runners) {
delete r;
}
std::cout << diff.count() << " micro seconds" << ", run count " << runCount << std::endl;
std::cout << "avg:" << diff.count() / (double)runCount << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment