Home > Backend Development > C++ > body text

Why Does Sleep(1) Seem to Sleep for 15ms in Windows?

Susan Sarandon
Release: 2024-10-28 00:23:02
Original
635 people have browsed it

Why Does Sleep(1) Seem to Sleep for 15ms in Windows?

Sleep() Function Behavior in Windows

When calling the Sleep() function, a thread typically suspends execution for the specified duration. However, in some cases, it may seem that the thread sleeps for a longer period.

In Windows versions such as Windows 7, Sleep() operates on a time quantum. This means that any non-zero delay is rounded up to the nearest quantum, which may result in slightly longer sleep durations.

A common symptom of this behavior is that a call to Sleep(1) may actually cause a sleep of around 15ms. This is because the operating system scheduler typically uses a quantum of 15.6ms.

To illustrate this, a code snippet is provided:

<code class="cpp">#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;
    }
}</code>
Copy after login

If executed on Windows 7, this code will likely report sleep durations around 15ms instead of 1ms.

Therefore, it's typical behavior for Sleep() to sleep for a slightly longer period than the specified delay due to the time quantum system employed by Windows.

The above is the detailed content of Why Does Sleep(1) Seem to Sleep for 15ms in Windows?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!