Sleep operation in C++, platform : windows Sleep operation in C++, platform : windows windows windows

Sleep operation in C++, platform : windows


Or if you are using Visual Studio 2010 (or another c++0x aware compiler) use

#include <thread>#include <chrono>std::this_thread::sleep();// orstd::this_thread::sleep_for(std::chrono::milliseconds(10));

With older compilers you can have the same convenience using the relevant Boost Libraries

Needless to say the major benefit here is portability and the ease of converting the delay parameter to 'human' units.


You could use the Sleep function from Win32 API.


the windows task scheduler has a granularity far above 1ms (generally, 20ms). you can test this by using the performance counter to measure the time really spent in the Sleep() function. (using QueryPerformanceFrequency() and QueryPerformanceCounter() allows you to measure time down to the nanosecond). note that Sleep(0) makes the thread sleep for the shortest period of time possible.

however, you can change this behavior by using timeBeginPeriod(), and passing a 1ms period. now Sleep(0) should return much faster.

note that this function call was made for playing multimedia streams with a better accuracy. i have never had any problem using this, but the need for such a fast period is quite rare. depending on what you are trying to achieve, there may be better ways to get the accuracy you want, without resorting to this "hack".