我试图获得 1 毫秒的延迟,但延迟增加了 15 倍。我也尝试过使用 WindowsSleep(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 https://i.stack.imgur.com/AVZDV.png
你没有得到预期的结果,因为你的期望落空了。sleep_for
不是等待确切的时间。从参考参数 https://en.cppreference.com/w/cpp/thread/sleep_for:
阻塞当前线程的执行at least指定的
睡眠持续时间。
这个功能阻塞时间可能超过 sleep_duration由于
调度或资源争用延迟。
该标准建议使用稳定的时钟来测量
期间。如果实现使用系统时钟,则等待
时间也可能对时钟调整敏感。
精确的计时通常需要专用硬件。对于台式电脑来说 1 毫秒的预期是相当乐观的。
最重要的是,您测量的时间不仅来自sleep_for
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)