boost::thread_sleep vs boost::chrono::thread_clock inconsistent

Viewed 471

When I run this code

#include <iostream>
#include <boost/thread.hpp>
#include <boost/chrono/thread_clock.hpp>

void foo() {
    boost::this_thread::sleep(boost::posix_time::microseconds(500));
}


int main() {
    boost::chrono::thread_clock::time_point start = boost::chrono::thread_clock::now();    
    foo();   
    boost::chrono::thread_clock::time_point stop = boost::chrono::thread_clock::now();    
    std::cout << "duration = " 
              << boost::chrono::duration_cast<boost::chrono::microseconds>(stop-start).count() 
              << " microsec\n";
}

I get the following output:

duration = 121 microsec
duration = 121 microsec
duration = 110 microsec
duration = 114 microsec

Also when I replace the 500 with a different value, eg 200, the output is always around 100. Compiling with -O3. Why is the timing not consistent?

PS: I read that sleep is deprecated, but when I replace it with

boost::this_thread::sleep_for(boost::chrono::microseconds(200));

the output is in the range of ~20 microseconds.

1 Answers
Related