【发布时间】:2019-04-23 19:24:39
【问题描述】:
我正在尝试使用 while 循环来创建一个持续测量 3000μs (3 ms) 的计时器,虽然它大部分时间都在工作,但其他时候计时器可能会延迟多达 500μs。为什么会发生这种情况,有没有更精确的方法来制作这样的计时器?
int getTime() {
chrono::microseconds μs = chrono::duration_cast< chrono::microseconds >(
chrono::system_clock::now().time_since_epoch() //Get time since last epoch in μs
);
return μs.count(); //Return as integer
}
int main()
{
int target = 3000, difference = 0;
while (true) {
int start = getTime(), time = start;
while ((time-start) < target) {
time = getTime();
}
difference = time - start;
if (difference - target > 1) { //If the timer wasn't accurate to within 1μs
cout << "Timer missed the mark by " + to_string(difference - target) + " microseconds" << endl; //Log the delay
}
}
return 0;
}
我希望这段代码记录的延迟始终在 5 微秒左右,但 the console output looks like this。
编辑澄清:我在 Windows 10 Enterprise Build 16299 上运行,但该行为在 Debian 虚拟机上仍然存在。
【问题讨论】:
-
您在 RTOS 上运行吗?如果没有,不要期待任何事情。
-
Windows 10 Enterprise Build 16299,尽管该行为在 Debian 虚拟机上仍然存在。
-
在多任务操作系统上,当您的应用程序运行像这样的无限循环并且永不休眠时,操作系统可能会任意将其暂停以给其他进程一个时间片。这可能是一个原因。
-
stackoverflow.com/q/37444594/2785528 的可能重复项。另请参阅我在stackoverflow.com/a/37445086/2785528 的回答。
标签: c++