Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timeout resolution of WaitForSingleObject

Tags:

winapi

When I wait on a non-signaled Event using the WaitForSingleObject function, I find that in some cases the call will return WAIT_TIMEOUT in less than the specified timeout period. Simply looping on the call with a timeout set to 1000ms, I've seen the call return in periods as low as 990ms (running on WinXP). I'm using QueryPerformanceCounter to get a system-clock independent time measurement, so I don't think clock drift is likely to be an answer.

This behavior doesn't present any practical problems for me, but I'd like to understand it better. It looks like it may be working at roughly the resolution of a timer tick. Does Microsoft publish any further details on the precision of this function? Should I expect greater precision in Vista?

like image 536
Chris Loer Avatar asked May 21 '09 21:05

Chris Loer


1 Answers

Yes, WaitForSingleObject uses the timer tick resolution, it does not use a high-resolution timer like QueryPerformanceCounter.

http://msdn.microsoft.com/en-us/library/ms687069(VS.85).aspx, the MSDN article on "Wait Functions" expands on this:

The accuracy of the specified time-out interval depends on the resolution of the system clock. The system clock "ticks" at a constant rate. If the time-out interval is less than the resolution of the system clock, the wait may time out in less than the specified length of time. If the time-out interval is greater than one tick but less than two, the wait can be anywhere between one and two ticks, and so on.

This article also explains how to use timeBeginPeriod to increase system clock resolution - but this is not recommended.

I can think of several reasons why. First, a higher resolution is not needed for nearly all use cases of WaitForSingleObject. Using a high-resolution timer would require the kernel to constantly poll the timer (not feasible since kernel code is not guaranteed to be always running) or reprogram it frequently to generate an interrupt (since there could be multiple WaitForSingleObjects and most likely only a single programmable interrupt).

On the other hand, there already is a timing source that is constantly updatable at a resolution that is more than good enough for WaitForSingleObject, SetWaitableTimer, and Sleep.

like image 81
Michael Avatar answered Sep 24 '22 13:09

Michael