問題描述
操作系統:Windows 7
OS: Windows 7
當調用 WinAPI Sleep() 函數作為 Sleep(1) 時,線程實際上會休眠 15 毫秒.我循環了 100 次,總睡眠時間是 1500 毫秒而不是 100 毫秒.
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.
這是常見行為還是我應該擔心我的 MOBO、CPU、Windows 安裝出現問題?
Is this common behavior or should I be concerced about something being wrong with my MOBO, CPU, Windows installion?
如果可能,您可以運行此代碼并發布睡眠時間有多長.我讓我的一個朋友運行了這個,他實際上在 1 毫秒內就完成了.
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;
}
似乎有些人得到 1ms 的原因是其他一些程序正在運行,將系統范圍的計時器分辨率設置為 1ms.默認情況下,這在 Windows 7 上應該是 15.6 毫秒.
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
是的.
Window 的線程調度程序在時間片上工作(確切長度取決于各種因素,包括 Windows 版本和版本).實際上,任何非零延遲都會向上舍入為一個完整的量程.
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.
這篇關于WinAPI Sleep() 函數調用休眠的時間比預期的要長的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!