"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does WinAPI Sleep(1) Result in a 15 Millisecond Pause?

Why Does WinAPI Sleep(1) Result in a 15 Millisecond Pause?

Published on 2024-11-08
Browse:157

Why Does WinAPI Sleep(1) Result in a 15 Millisecond Pause?

Understanding the Discrepancy in WinAPI Sleep() Function's Duration

When invoking the WinAPI Sleep() function with a parameter of 1 milliseconds, it is observed that the thread actually pauses for a much longer duration, typically around 15 milliseconds. This phenomenon raises concerns about potential system issues.

Time Quantization in Windows

Windows employs a time quantization mechanism for its thread scheduling. This means that the system schedules threads in discrete intervals, known as quantum. The exact duration of these intervals varies based on several factors, including the Windows version and edition. On average, Windows 7 operates with a time quantum of approximately 15.6 milliseconds.

Impact on Sleep() Duration

As a result of time quantization, any non-zero delay argument provided to Sleep() is rounded up to the nearest quantum. This explains why a Sleep(1) call actually pauses the thread for 15 milliseconds, which is the closest time quantum to 1 millisecond.

Verification

To verify this behavior, you can execute the provided code snippet. Running the code may yield different results depending on the system's timer resolution settings. If the system-wide timer resolution has been manually set to 1 millisecond, you may observe shorter sleep durations. However, by default, Windows 7 uses a timer resolution of 15.6 milliseconds, leading to the extended sleep times observed.

Conclusion

The discrepancy in the Sleep() function's duration is attributed to the inherent time quantization mechanism in Windows' thread scheduler. This rounding up ensures that thread scheduling is performed efficiently and predictably, preventing potential thread scheduling conflicts.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3