OS: Windows 7
When calling the WinAPI Sleep() function as Sleep(1) the thread actually sleeps for 15ms. I did it 100 times in a loop and the total sleep time was 1500ms instead of 100.
Is this common behavior or should I be concerced about something being wrong with my MOBO, CPU, Windows installion?
EDIT: If possible could you run this code and post how long the sleep time was. I let a friend of mine run this, and he actually had it all at 1ms.
#include <iostream>
#include <ctime>
#include <Windows.h>
void test(void)
{
std::cout << "Testing 1ms sleep." << std::endl;
for (unsigned int i = 0; i < 10; i++)
{
std::clock_t startClocks = std::clock();
Sleep(1);
std::clock_t clocksTaken = std::clock() - startClocks;
std::cout << "Time: " << clocksTaken << "ms." << std::endl;
}
}
int main(void)
{
test();
std::cin.sync();
std::cin.get();
return 0;
}
EDIT2: It seems that the reason why some people are getting 1ms is that some other program is running that sets the system-wide timer resolution to 1ms. By default this should be 15.6ms on Windows 7.
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.
Sleep
can cause the thread to sleep for longer than the timeout specified, it only guarantees that the thread will sleep for at least that length of time.
From the documentation:
After the sleep interval has passed, the thread is ready to run. If you specify 0 milliseconds, the thread will relinquish the remainder of its time slice but remain ready. Note that a ready thread is not guaranteed to run immediately. Consequently, the thread may not run until some time after the sleep interval elapses. For more information, see Scheduling Priorities.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With