Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sleep operation in C++, platform : windows

Tags:

c++

sleep

windows

I want to perform the above mentioned operation in Milliseconds as the unit. Which library and function call should I prefer ?

Ty.

like image 627
Pumpkin Avatar asked Oct 30 '11 16:10

Pumpkin


People also ask

What is the function of sleep in Windows?

Sleep uses very little power, your PC starts up faster, and you're instantly back to where you left off. You don't have to worry that you'll lose your work because of your battery draining because Windows automatically saves all your work and turns off the PC if the battery is too low.

What header is sleep in C?

Answer: The header for sleep is “unistd. h” for LINUX/UNIX Operating system and “Windows. h” for the Windows Operating system.

What does sleep mean in code?

In computing, sleep is a command in Unix, Unix-like and other operating systems that suspends program execution for a specified time.


3 Answers

Or if you are using Visual Studio 2010 (or another c++0x aware 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 relevant Boost Libraries

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

like image 137
sehe Avatar answered Oct 21 '22 14:10

sehe


You could use the Sleep function from Win32 API.

like image 26
Branko Dimitrijevic Avatar answered Oct 21 '22 12:10

Branko Dimitrijevic


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".

like image 42
Adrien Plisson Avatar answered Oct 21 '22 12:10

Adrien Plisson