I have a simple code running on my 64 bit machine, Windows 7 as a standard windows application :
do {
DWORD getCurrentTick = GetTickCount();;
Sleep(20);
DWORD nextTick = GetTickCount();
printf("Tick = %d\n", nextTick - getCurrentTick);
} while(TRUE);
I know that a user mode thread sleep is not guaranteed to wake on the requested time but the weird thing is that windows wakes before time comes. look at my output :
Tick = 15
Tick = 16
Tick = 16
Tick = 31
Tick = 15
Tick = 16
Tick = 15
Tick = 16
Tick = 31
My question is how come it wakes before my requested time ? and what can I do to make it more precise ?
The OS has a particular quantum for thread scheduling which impacts the accuracy of thread waits. It defaults to 15 ms, so a Sleep of 20 is going to end up either before it or after it. This is "by design".
It is possible in a Win32 desktop app to improve the accuracy by using the old WinMM function timeBeginPeriod(1); but this (a) is a global setting, and (b) greatly reduces the efficiency of the power management.
You should use waitable timer events and not Sleep, but you will still be subject to the thread scheduling quantum for accuracy when the thread is halted.