gpt4 book ai didi

c++ - 获取错误的毫秒延迟值

转载 作者:行者123 更新时间:2023-12-01 14:37:21 25 4
gpt4 key购买 nike

我试图获得 1 毫秒的延迟,但延迟增加了 15 倍。我还尝试过使用 Windows 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;
}
}
}

该程序的输出:/image/AVZDV.png

最佳答案

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

Blocks the execution of the current thread for at least the specified 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 毫秒预期是相当乐观的。

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

关于c++ - 获取错误的毫秒延迟值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62445592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com