Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Sleep(500) cost more than 500ms?

Tags:

c++

sleep

winapi

I used Sleep(500) in my code and I used getTickCount() to test the timing. I found that it has a cost of about 515ms, more than 500. Does somebody know why that is?

like image 727
kookoo121 Avatar asked Nov 12 '15 12:11

kookoo121


3 Answers

Because Win32 API's Sleep isn't a high-precision sleep, and has a maximum granularity.

The best way to get a precision sleep is to sleep a bit less (~50 ms) and do a busy-wait. To find the exact amount of time you need to busywait, get the resolution of the system clock using timeGetDevCaps and multiply by 1.5 or 2 to be safe.

like image 112
orlp Avatar answered Nov 06 '22 02:11

orlp


sleep(500) guarantees a sleep of at least 500ms.

But it might sleep for longer than that: the upper limit is not defined.

In your case, there will also be the extra overhead in calling getTickCount().

Your non-standard Sleep function may well behave in a different matter; but I doubt that exactness is guaranteed. To do that, you need special hardware.

like image 43
Bathsheba Avatar answered Nov 06 '22 01:11

Bathsheba


As you can read in the documentation, the WinAPI function GetTickCount()

is limited to the resolution of the system timer, which is typically in the range of 10 milliseconds to 16 milliseconds.

To get a more accurate time measurement, use the function GetSystemDatePreciseAsFileTime

Also, you can not rely on Sleep(500) to sleep exactly 500 milliseconds. It will suspend the thread for at least 500 milliseconds. The operating system will then continue the thread as soon as it has a timeslot available. When there are many other tasks running on the operating system, there might be a delay.

like image 18
Philipp Avatar answered Nov 06 '22 02:11

Philipp