Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WinAPI Sleep() function call sleeps for longer than expected

Tags:

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.

like image 721
NFRCR Avatar asked Mar 01 '12 14:03

NFRCR


2 Answers

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.

like image 159
Richard Avatar answered Sep 18 '22 13:09

Richard


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.

like image 38
obmarg Avatar answered Sep 18 '22 13:09

obmarg