WinAPI Sleep() 函数调用休眠的时间比预期的要长

WinAPI Sleep() function call sleeps for longer than expected(WinAPI Sleep() 函数调用休眠的时间比预期的要长)
本文介绍了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() 函数调用休眠的时间比预期的要长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Prevent class inheritance in C++(防止 C++ 中的类继承)
Why should I declare a virtual destructor for an abstract class in C++?(为什么要在 C++ 中为抽象类声明虚拟析构函数?)
Why is Default constructor called in virtual inheritance?(为什么在虚拟继承中调用默认构造函数?)
C++ cast to derived class(C++ 转换为派生类)
C++ virtual function return type(C++虚函数返回类型)
Is there any real risk to deriving from the C++ STL containers?(从 C++ STL 容器派生是否有任何真正的风险?)