c++ - clock_gettime 返回无意义的值

标签 c++ linux time

我正在尝试在 Linux 中模拟一个以恒定速率下降的点。为此,我需要将时间精确到毫秒。现在这部分没问题,但我遇到了 clock_gettime 问题。

当“tv_nsec”字段环绕到大约 100000000 时,它开始回到接近零的位置,并且 clock_gettime 检索的时间早于上一次迭代检索的时间。请注意,这不会在每次字段换行时发生,但确实会发生。

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

Iteration:

gettime.seconds: 1362720808 , gettime.us: 993649771, total: 1362721801649 us
delta: 0.014

Another iteration:

gettime.seconds: 1362720808 , gettime.us: 993667981, total: 1362721801667 us
delta: 0.015

Another iteration:

gettime.seconds: 1362720808 , gettime.us: 993686119, total: 1362721801686 us
delta: 0.015

Iteration 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/

相关文章:

c++ - 如何添加自定义关键字以 clang 格式处理为 "class"?

C++ 在类中声明静态枚举与枚举

c++ - 有没有办法在不复制所有像素的情况下将现有的像素数组转换为 BITMAP?

c - 如何拦截 gtk 窗口关闭按钮单击?

c++ - 如何明智地实现96条件?

algorithm - 如何计算两次最少到场人数

c++ - 原子增量和返回计数器

java - Linux : A simple Linux Script is showing some comamnds on to the screen

linux - 如何在 Debian linux 控制台上显示中文或日文?

c++ - 如何从 boost::posix_time::ptime 获取秒数