【问题标题】:clock_gettime returning a nonsense valueclock_gettime 返回一个无意义的值
【发布时间】:2013-03-08 06:07:48
【问题描述】:

我试图在 linux 中模拟一个以恒定速率下降的点。为此,我需要获得毫秒分辨率的时间。现在这部分很好,但我遇到了 clock_gettime 的问题。

当 'tv_nsec' 字段回绕到大约 100000000 时,它会从零附近开始,clock_gettime 检索到的时间是在上一次迭代检索到的时间之前。请注意,并非每次字段换行时都会发生这种情况,但确实会发生。

为了调试,我让它写入了从 clock_gettime 返回的值和检索的增量值:

迭代:

gettime.seconds:1362720808,gettime.us:993649771,总计:1362721801649 us
增量:0.014

另一个迭代:

gettime.seconds:1362720808,gettime.us:993667981,总计:1362721801667 us
增量:0.015

另一个迭代:

gettime.seconds:1362720808,gettime.us:993686119,总计:1362721801686 us
增量:0.015

有问题的迭代:

gettime.seconds:1362720809,gettime.us:20032630,总计:1362720829032 us
增量:-972.661

请注意,增量以秒为单位,其计算方法是将毫秒除以 1000,再加上从过去的时间中减去未来的时间(等于负数),然后再除以 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”编译时钟功能。

这将循环直到问题发生,即由于时间的原因,增量为负。在我的电脑上只需几秒钟。

很抱歉这个冗长的问题,但感谢您提前获得的任何帮助:)

【问题讨论】:

  • 为什么在您的退货声明中使用 0.5?

标签: c++ linux time


【解决方案1】:

tv_nsec纳秒,即一秒的十亿分之一 (1 / 1,000,000,000)。但是,您的计算将其视为微秒。

解决方法如下:

return ((ts.tv_sec * 1000) + (ts.tv_nsec / 1000000)) + 0.5;
                                               ^^^

【讨论】:

  • 非常感谢,我在想这不是我的错。我不太确定我是怎么错过的。
猜你喜欢
  • 2011-10-10
  • 1970-01-01
  • 2019-05-04
  • 2016-08-09
  • 2019-12-03
  • 2011-11-28
  • 2013-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多