获取毫秒延迟的错误值
Getting wrong value for Millisecond delay
我试图获得 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
。
发生这种情况是因为两件事。
-
等待不是你唯一在做的事情,增量和IF语句检查也需要时间。
-
没有时钟是完美的
另外,如果你想要一个无限循环while(true)
更好看
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- 获取毫秒延迟的错误值
- 为什么延迟指令导致编译器错误
- 错误保持活动状态延迟
- C 延迟负载DLL链接器错误
- 使用延迟加载加载正确的库 - 返回值类型错误
- 基于静态条件延迟对非嵌套类型的引用,且没有编译错误