其他分享
首页 > 其他分享> > c – ‘clock_gettime’和’gettimeofday’的奇怪时序结果

c – ‘clock_gettime’和’gettimeofday’的奇怪时序结果

作者:互联网

我想检查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,同样悲伤的结果.

解决方法:

您只是比较struct timespec的tv_nsec成员,同时您还应该比较tv_sec成员:

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

同样,您应该比较struct timeval的tv_sec和tv_usec成员以获取已用时间:

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

标签:c-2,linux,sleep,timing,gettimeofday
来源: https://codeday.me/bug/20190530/1182246.html