Sleep() 不准确吗?

编程入门 行业动态 更新时间:2024-10-25 19:28:54
本文介绍了Sleep() 不准确吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 12:59:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1395146.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不准确   Sleep

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!