我正在寻求改善或请求当前的延迟/睡眠方法。 C ++ [英] I'm looking to improve or request my current delay / sleep method. c++

查看:82
本文介绍了我正在寻求改善或请求当前的延迟/睡眠方法。 C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我正在编码一个项目,该项目要求在多台计算机上具有精确的延迟时间。目前,这是我在论坛上找到的代码。这是下面的代码。

Currently I am coding a project that requires precise delay times over a number of computers. Currently this is the code I am using I found it on a forum. This is the code below.

{
    LONGLONG timerResolution;
    LONGLONG wantedTime;
    LONGLONG currentTime;

    QueryPerformanceFrequency((LARGE_INTEGER*)&timerResolution);
    timerResolution /= 1000;

    QueryPerformanceCounter((LARGE_INTEGER*)&currentTime);
    wantedTime = currentTime / timerResolution + ms;
    currentTime = 0;
    while (currentTime < wantedTime)
    {
        QueryPerformanceCounter((LARGE_INTEGER*)&currentTime);
        currentTime /= timerResolution;
    }
}

基本上,我遇到的问题是当我开始调用该函数时,CPU约为16-20%。通常的Sleep();使用零CPU,但是根据我在多个论坛上看到的信息,这是非常不准确的,这是在权衡CPU使用率的准确性时要进行的权衡,但是我认为在设置此睡眠方法之前,我最好提出这个问题。

Basically the issue I am having is this uses alot of CPU around 16-20% when I start to call on the function. The usual Sleep(); uses Zero CPU but it is extremely inaccurate from what I have read from multiple forums is that's the trade-off when you trade accuracy for CPU usage but I thought I better raise the question before I set for this sleep method.

推荐答案

您可以将Windows计时器分辨率设置为最小值(通常为1毫秒),以使 Sleep()精确到1毫秒。默认情况下,它的精确度最高可达约15 ms。 Sleep()文档。

You can set the Windows timer resolution to minimum (usually 1 ms), to make Sleep() accurate up to 1 ms. By default it would be accurate up to about 15 ms. Sleep() documentation.

请注意,如果其他程序正在消耗CPU时间,则可能会延迟执行,但是如果您正在等待计时器,也会发生这种情况。

Note that your execution can be delayed if other programs are consuming CPU time, but this could also happen if you were waiting with a timer.

#include <timeapi.h>

// Sleep() takes 15 ms (or whatever the default is)
Sleep(1);

TIMECAPS caps_;
timeGetDevCaps(&caps_, sizeof(caps_));
timeBeginPeriod(caps_.wPeriodMin);

// Sleep() now takes 1 ms
Sleep(1);

timeEndPeriod(caps_.wPeriodMin);

这篇关于我正在寻求改善或请求当前的延迟/睡眠方法。 C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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