WinAPI Sleep() function call sleeps for longer than expected(WinAPI Sleep() 函数调用休眠的时间比预期的要长)
问题描述
操作系统: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() 函数调用休眠的时间比预期的要长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:WinAPI Sleep() 函数调用休眠的时间比预期的要长


基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01