Skip to content

Instantly share code, notes, and snippets.

@teknoman117
Created April 7, 2015 13:50
Show Gist options
  • Save teknoman117/97e73adb7c667937f7b9 to your computer and use it in GitHub Desktop.
Save teknoman117/97e73adb7c667937f7b9 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <ctime>
#include <chrono>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
// interval = t1 - t2
long GetIntervalBetween (struct timespec t1, struct timespec t2)
{
return ((1e9 * t1.tv_sec) + t1.tv_nsec) - ((1e9 * t2.tv_sec) + t2.tv_nsec);
}
int main (int argc, char** argv)
{
mutex workMutex;
mutex printMutex;
condition_variable workCondition;
struct timespec lockTime;
// Spin off a thread to compare time against
for(unsigned int i = 0; i < thread::hardware_concurrency(); i++)
{
thread([&workMutex, &workCondition, &lockTime, &printMutex, i] ()
{
while(1)
{
// Wait on the condition variable
unique_lock<mutex> lock(workMutex);
workCondition.wait(lock);
lock.unlock();
// Measure the current time
struct timespec currentTime;
clock_gettime(CLOCK_MONOTONIC_RAW, &currentTime);
float interval = GetIntervalBetween(currentTime, lockTime);
// Display the time difference
{
lock_guard<mutex> lock2(printMutex);
cout << "[WORKER " << i << "]: wakeup latency = " << interval / 1e6 << " ms" << endl;
}
}
}).detach();
}
// Main thread
while(1)
{
// Sleep for a random amount of time
int sleeptime = rand() % 1000;
cout << "[MAIN]: sleep for " << sleeptime << " ms" << endl;
this_thread::sleep_for(chrono::milliseconds(sleeptime));
{
lock_guard<mutex> lock(workMutex);
clock_gettime(CLOCK_MONOTONIC_RAW, &lockTime);
}
workCondition.notify_all();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment