Sleep for milliseconds Sleep for milliseconds linux linux

Sleep for milliseconds


In C++11, you can do this with standard library facilities:

#include <chrono>#include <thread>
std::this_thread::sleep_for(std::chrono::milliseconds(x));

Clear and readable, no more need to guess at what units the sleep() function takes.


Note that there is no standard C API for milliseconds, so (on Unix) you will have to settle for usleep, which accepts microseconds:

#include <unistd.h>unsigned int microseconds;...usleep(microseconds);


To stay portable you could use Boost::Thread for sleeping:

#include <boost/thread/thread.hpp>int main(){    //waits 2 seconds    boost::this_thread::sleep( boost::posix_time::seconds(1) );    boost::this_thread::sleep( boost::posix_time::milliseconds(1000) );    return 0;}

This answer is a duplicate and has been posted in this question before. Perhaps you could find some usable answers there too.