Winapi Sleep() Function Call Sleeps for Longer Than Expected

WinAPI Sleep() function call sleeps for longer than expected

Is this common behavior

It is.

Window's thread scheduler works on a time quantum (exact length depends of various factors including Windows version and edition). Effectively any non-zero delay is rounded up to a complete quantum.

Windows Sleep inconsistency?

A waitable timer (CreateWaitableTimer and WaitForSingleObject or friends) is much better for periodic wakeup.

However, in your case you probably should just enable VSYNC.

WinAPI: Are waitable timers resumed after a sleep state?

  1. According to System Wake-up Events, Your application can restore a computer that is in a sleep state to the working state by using a scheduled timer or a device event. This is known as a wake-up event. Use a waitable timer object to specify the time at which the system should wake.
  2. According to Operational Mode Events, When an application receives notification that the system is about to enter sleep, it should perform any necessary operations quickly and return out of the message loop. The system allows for a maximum of two seconds per application when handling this message before timing out. So It's good practice to interrupt the scheduled actions by handling some power-management events.

Why is the sleep-time of Sleep(1) seems to be variable in Windows?

I've not heard about the resolution jumping around like that on its own, but in general the resolution of Sleep follows the clock tick of the task scheduler. So by default it's usually 10 or 15 ms, depending on the edition of Windows. You can set it manually to 1 ms by issuing a timeBeginPeriod.

Precise thread sleep needed. Max 1ms error

From the question tags I suppose you are on windows.
Take a look at Multimedia Timers, they advertise precision under 1ms.
Another options is to use Spin Locks but this will basically keep a cpu core at maximum usage.

Sleep function in c in windows. Does a function with better precision exist?

No, not really. When you tell your program to sleep, you're giving up the processor and letting the operating system decide what to do next. Once the operating system is in control, it decides when to give your program another slice of processing time. This is why you can specify a minimum, but there's no guarantee that the OS will get back to your process at any particular time.



Related Topics



Leave a reply



Submit