我正在尝试在 Linux 中模拟一个以恒定速率下降的点。为此,我需要将时间精确到毫秒。现在这部分没问题,但我遇到了 clock_gettime 问题。
当“tv_nsec”字段环绕到大约 100000000 时,它开始回到接近零的位置,并且 clock_gettime 检索的时间早于上一次迭代检索的时间。请注意,这不会在每次字段换行时发生,但确实会发生。
为了调试,我让它写入从 clock_gettime 返回的值和检索的增量值:
Iteration:
gettime.seconds: 1362720808 , gettime.us: 993649771, total: 1362721801649 us
delta: 0.014Another iteration:
gettime.seconds: 1362720808 , gettime.us: 993667981, total: 1362721801667 us
delta: 0.015Another iteration:
gettime.seconds: 1362720808 , gettime.us: 993686119, total: 1362721801686 us
delta: 0.015Iteration in question:
gettime.seconds: 1362720809 , gettime.us: 20032630, total: 1362720829032 us
delta: -972.661
请注意,delta 以秒为单位,计算方法是将毫秒除以 1000,结合过去的时间减去 future 的时间等于负值,然后除以 1000,得到增量为正。
重现问题的代码在这里:
#include <iostream>
#include <sys/time.h>
using namespace std
double prevMillis = 0.0;
double getMillis()
{
timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
cout << "gettime.seconds: " << ts.tv_sec << " , gettime.us: " << ts.tv_nsec << ", total: " << ((ts.tv_sec * 1000) + (ts.tv_nsec / 1000)) << " ms" << endl;
return ((ts.tv_sec * 1000) + (ts.tv_nsec / 1000)) + 0.5;
}
int main()
{
double delta = 0.0;
prevMillis = getMillis();
while(delta >= 0)
{
delta = (getMillis() - prevMillis) / 1000;
prevMillis = getMillis();
cout << "Delta: " << delta << endl << endl;
}
return 0;
}
请注意,必须为时钟功能使用“-lrt”进行编译。
这将循环直到问题发生,即由于时间的原因增量为负。在我的 PC 上只需要几秒钟。
很抱歉这个冗长的问题,但感谢我提前获得的任何帮助:)
最佳答案
tv_nsec
是 纳秒,即一秒的十亿分之一 (1/1,000,000,000)。然而,您的计算将其视为微秒。
修复方法如下:
return ((ts.tv_sec * 1000) + (ts.tv_nsec / 1000000)) + 0.5;
^^^
关于c++ - clock_gettime 返回无意义的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15287778/