4

我正在将一个 C 项目从 Solaris 移植到 Linux 并重新编译它。在 logger.c 中,sys/time.h 的 gethrtime() 函数不能为 Linux 编译。如何将其移植到 Linux?Linux中有这个的替代品吗?

4

3 回答 3

4

您正在寻找的功能是clock_gettime

struct timespec t;
if (clock_gettime(CLOCK_MONOTONIC, &t) == -1) {
    perror("clock_gettime for CLOCK_MONOTONIC failed");
} else {
    printf("mono clock timestamp: %ld.%09ld\n", t.tv_sec, t.tv_nsec);
}

参数从未指定的CLOCK_MONOTONIC起点获取时间。这与CLOCK_REALTIME哪个获取挂钟时间不同。

在大多数实现中,分辨率将以纳秒为单位,但是您可以通过调用找到确切的分辨率clock_getres

struct timespec t;
if (clock_getres(CLOCK_MONOTONIC, &t) == -1) {
    perror("clock_getres for CLOCK_MONOTONIC failed");
} else {
    printf("mono clock resolution: %ld.%09ld\n", t.tv_sec, t.tv_nsec);
}
于 2018-03-12T18:24:35.427 回答
3

这是我 10 多年以来所拥有的:

头文件:

#ifdef __linux
typedef uint64_t hrtime_t;
hrtime_t gethrtime( void );
#endif

源代码:

#ifdef __linux

hrtime_t gethrtime( void )
{
    struct timespec ts;
    hrtime_t result;

#ifdef CLOCK_MONOTONIC_HR
    clock_gettime( CLOCK_MONOTONIC_HR, &ts );
#else
    clock_gettime( CLOCK_MONOTONIC, &ts );
#endif

    result = 1000000000LL * ( hrtime_t ) ts.tv_sec;
    result += ts.tv_nsec;

    return( result );
}

#endif

它可能应该进行一些错误检查,但由于gethrtime()没有任何方法可以返回错误,所以我没有看到任何理由在此处添加它。

于 2018-03-12T20:04:47.027 回答
1

阅读时间(7)。您可能想使用clock_gettime(2)

于 2018-03-12T18:18:02.180 回答