Sleep operation in C ++, platform: windows

I want to perform the above operation in milliseconds as a unit. Which library and function should I use?

Ty.

+8
c ++ windows sleep
source share
4 answers

You can use Sleep from the Win32 API.

+5
source share

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

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

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

Needless to say, the main advantage of portability and the simplicity of converting the delay parameter to โ€œhumanโ€ units.

+6
source share

The Windows Task Scheduler has a granularity far above 1 ms (typically 20 ms). you can check this using the performance counter to measure the time actually spent on the Sleep() function. (using QueryPerformanceFrequency() and QueryPerformanceCounter() allows you to measure time to nanoseconds). note that Sleep(0) causes the thread to sleep for the shortest period of time.

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

Please note that this function call was made to play multimedia streams with better accuracy. I have never had a problem with this, but the need for such a quick period is quite rare. depending on what you are trying to achieve, there may be better ways to get the required accuracy without resorting to this โ€œhackingโ€.

+2
source share
0
source share

All Articles