操作系统: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() 函数调用休眠的时间比预期的要长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!