获取毫秒延迟的错误值

Getting wrong value for Millisecond delay

本文关键字:错误 延迟 获取      更新时间:2023-10-16

我试图获得 1 毫秒的延迟,但我得到了 15 倍的延迟。我也尝试过使用窗口Sleep(1)功能,这也给了我相同的结果。

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

哪里工作,延迟 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不是等待确切的时间。从 cpp 首选项:

至少阻止当前

线程的执行指定的sleep_duration。

由于以下原因,此功能的阻塞时间可能会超过 sleep_duration计划或资源争用延迟。

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

精确的时序通常需要专用硬件。期望台式电脑的 1 毫秒是相当乐观的。

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

发生这种情况是因为两件事。

  1. 等待不是你唯一在做的事情,增量和IF语句检查也需要时间。

  2. 没有时钟是完美的

另外,如果你想要一个无限循环while(true)更好看