Sleep() 不准确吗? [英] Is Sleep() inaccurate?

查看:66
本文介绍了Sleep() 不准确吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个计时系统,我将实现一个计时器类.

I'm working on a timing system and I'll implement a timer class.

#include <windows.h>
#include <stdio.h>
#include <time.h>

int main()
{
    clock_t t1, t2;
    t1 = clock();
    Sleep(10);
    t2 = clock();
    printf("%i\n", (int)(t2 - t1));
    return 0;
}

这个程序应该打印10"但它打印15"或16".我需要更准确,小于 1 毫秒!建议?(也许与 select() 的超时?)

This program should print "10" but it prints "15" or "16". I need more accurate which is less than 1 ms! Suggestions? (maybe with select()'s timeout?)

注意:我已经在 Windows 7 Ultimate x86 上运行了这个程序.使用 MinGW (C/C++) x86 编译的程序.

NOTE: I've run this program on Windows 7 Ultimate x86. Program compiled with MinGW (C/C++) x86.

现在我想>>

推荐答案

Sleep() 精确到操作系统的时钟中断率.默认情况下,Windows 每秒滴答 64 次.或者如您所见,每 15.625 毫秒一次.

Sleep() is accurate to the operating system's clock interrupt rate. Which by default on Windows ticks 64 times per second. Or once every 15.625 msec, as you found out.

您可以提高该速率,调用 timeBeginPeriod(10).完成后使用 timeEndPeriod(10) .您仍然受到正常线程调度延迟的影响,因此您仍然无法保证您的线程将在 10 毫秒后恢复运行.当机器负载很重时不会.使用 SetThreadPriority() 提高优先级,增加它的几率.

You can increase that rate, call timeBeginPeriod(10). Use timeEndPeriod(10) when you're done. You are still subject to normal thread scheduling latencies so you still don't have a guarantee that your thread will resume running after 10 msec. And won't when the machine is heavily loaded. Using SetThreadPriority() to boost the priority, increasing the odds that it will.

这篇关于Sleep() 不准确吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆