获得错误的毫秒延迟值 [英] Getting wrong value for Millisecond delay

查看:56
本文介绍了获得错误的毫秒延迟值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获得 1 毫秒的延迟,但我得到了 15 倍的延迟.我也尝试过使用 windows Sleep(1) 函数,这也给了我相同的结果.

I am trying to get 1 millisecond delay but i am getting 15 times higher.I have also tried with windows Sleep(1) function which was also giving me the same result.

为什么我没有得到精确的毫秒延迟?

why am i not getting exact millisecond delay?

延迟 1 秒.

#include <iostream>
#include <Windows.h>
#include <thread>
#include <chrono>

void counter1();

auto main() -> int
{

    std::thread p(&counter1);
    p.join();
    return 0;
}

void counter1()
{
    int nStep = 0;
    const int STEP = 1000;
    auto start = std::chrono::high_resolution_clock::now();
    for (;;)
    {
        ++nStep; // incrementing every millisecond
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
        if (nStep == STEP) {  // compares at second
            auto duration = std::chrono::high_resolution_clock::now() - start;
            std::cout << "counter took " <<
                std::chrono::duration_cast<std::chrono::seconds>(duration).count()
                << "seconds \n";
            start = std::chrono::high_resolution_clock::now();
            nStep = 0;
        }
    }
}

该程序的输出:https://i.stack.imgur.com/AVZDV.png

推荐答案

您没有得到预期的结果,因为您的期望落空了.sleep_for 不是等待确切的时间.来自 cppreference:

You are not getting the expected results, because your expectations are off. sleep_for is not to wait for exact time. From cppreference:

阻止当前线程的执行至少指定的sleep_duration.

Blocks the execution of the current thread for at least the specified sleep_duration.

此功能可能阻塞的时间超过 sleep_duration,因为调度或资源争用延迟.

This function may block for longer than sleep_duration due to scheduling or resource contention delays.

标准建议使用稳定的时钟来测量期间.如果实现使用系统时钟,则等待时间也可能对时钟调整很敏感.

The standard recommends that a steady clock is used to measure the duration. If an implementation uses a system clock instead, the wait time may also be sensitive to clock adjustments.

精确计时通常需要专用硬件.预计台式机 1 毫秒是相当乐观的.

Exact timing typically requires dedicated hardware. Expecting 1ms from a desktop pc is rather optimistic.

最重要的是,您测量的时间不仅来自 sleep_for.

On top of that the time you measure is not only from sleep_for.

这篇关于获得错误的毫秒延迟值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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