Updated answer for C ++ 11:
Use the sleep_for and sleep_until :
#include <chrono> #include <thread> int main() { using namespace std::this_thread; // sleep_for, sleep_until using namespace std::chrono; // nanoseconds, system_clock, seconds sleep_for(nanoseconds(10)); sleep_until(system_clock::now() + seconds(1)); }
With these functions, you no longer need to constantly add new functions for better resolution: sleep , usleep , nanosleep , etc. sleep_for and sleep_until are template functions that can take any resolution values โโthrough chrono types; hours, seconds, femtoseconds, etc.
In C ++ 14, you can further simplify code with literal suffixes for nanoseconds and seconds :
#include <chrono> #include <thread> int main() { using namespace std::this_thread; // sleep_for, sleep_until using namespace std::chrono_literals; // ns, us, ms, s, h, etc. using std::chrono::system_clock; sleep_for(10ns); sleep_until(system_clock::now() + 1s); }
Please note that the actual duration of sleep depends on the implementation: you can ask to sleep for 10 nanoseconds, but the implementation may end up sleeping for a millisecond instead, if it is the shortest thing that it can do.
bames53 Mar 17 2018-12-12T00: 00Z
source share