I recently came across the need to sleep the current thread for an exact period of time. I know of two methods of doing so on a POSIX platform: using nanosleep()
or using boost::this_thread::sleep()
.
Out of curiosity more than anything else, I was wondering what the differences are between the two approaches. Is there any difference in precision, and is there any reason not to use the Boost approach?
nanosleep()
approach:
#include <time.h>
...
struct timespec sleepTime;
struct timespec returnTime;
sleepTime.tv_sec = 0;
sleepTime.tv_nsec = 1000;
nanosleep(&sleepTime, &returnTime);
Boost approach:
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread/thread.hpp>
...
boost::this_thread::sleep(boost::posix_time::nanoseconds(1000));
The few reasons why use boost that I can think of:
boost::this_thread::sleep()
is an
interruption point in boost.threadboost::this_thread::sleep()
can be
drop-in replaced by C++0x's
std::this_thread::sleep_until()
in
futureFor why not -- if you're not using threads at all, or of everything else in your project uses POSIX calls, then nanosleep()
makes more sense.
As for precision, on my system both boost and nanosleep() call the same system call, hrtimer_nanosleep()
. I imagine boost authors try to get the highest precision possible on each system and for me it happens to be the same thing as what nanosleep()
provides.