【问题标题】:strange timing results for 'clock_gettime' and 'gettimeofday'“clock_gettime”和“gettimeofday”的奇怪计时结果
【发布时间】:2012-07-29 01:14:09
【问题描述】:

我想检查clock_gettime 的可靠性,使用已弃用的gettimeofday 作为参考,但有时会得到奇怪的结果:

#include <stdio.h>
#include <sys/time.h>
#include <iostream>

void clock_gettime_test()
{
    struct timespec tp;
    clock_gettime(CLOCK_MONOTONIC_RAW, &tp);
    long a = tp.tv_nsec;
    usleep(250000);
    clock_gettime(CLOCK_MONOTONIC_RAW, &tp);
    long b = tp.tv_nsec;
    printf("clock_gettime (%ld - %ld): %lf msec\n", b, a, (b - a)/1000000.0);
}

void gettimeofday_test()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    long a = tv.tv_usec;
    usleep(250000);
    gettimeofday(&tv, NULL);
    long b = tv.tv_usec;
    printf("gettimeofday (%ld - %ld): %lf msec\n", b, a, (b - a)/1000.0);
}

int main()
{
    clock_gettime_test();
    gettimeofday_test();
    return 0;
}

构建和运行,我有时会得到正确的结果:

$ g++ -Wall play.cpp -lrt && ./a.out
clock_gettime (392441961 - 142299879): 250.142082 msec
gettimeofday (592906 - 342644): 250.262000 msec

但有时,我没那么幸运:

clock_gettime (155321165 - 905000848): -749.679683 msec
gettimeofday (352232 - 101938): 250.294000 msec

甚至:

clock_gettime (947857371 - 697373625): 250.483746 msec
gettimeofday (225208 - 974908): -749.700000 msec

我在 i686 和 amd64 上都试过了,得到了相似的结果。我也尝试了nanosleep,结果同样悲惨。

【问题讨论】:

  • 不确定您在此处测量的内容,因为无法保证 usleep() 在指定的超时时间过后准确唤醒。唯一的要求是它不会比这更早醒来。
  • 我只是在检查我能否获得更多或更少的 250 毫秒。

标签: c++ linux sleep timing gettimeofday


【解决方案1】:

您只是在比较struct timespectv_nsec 成员,而您还应该比较tv_sec 成员:

double msec = ((tpb.tv_sec - tpa.tv_sec) * 1000.0)
            + ((tpb.tv_nsec - tpa.tv_nsec) / 1000000.0);

同样,您应该比较struct timevaltv_sectv_usec 成员以获取经过的时间:

double msec = ((tvb.tv_sec - tva.tv_sec) * 1000.0)
            + ((tvb.tv_usec - tva.tv_usec) / 1000.0);

【讨论】:

    【解决方案2】:

    来自Unix,C, and C++ function reference

    一个timeval有两个 组件,两个整数。一(称为 tv_sec)正是 将按时间返回,即自 1970 年 1 月 1 日以来的秒数。 另一个(称为 tv_usec)是进入那个的微秒数 第二个。

    因此,tv_usec 将每秒重置一次。这就是为什么你会得到这个结果。考虑到秒数,您可能会有 1000 毫秒 - 749.679683 毫秒 ~ 250 毫秒。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-14
      相关资源
      最近更新 更多