任何时间函数保证为调用返回不同的值

Any Time Function Guarantee to Return Different Values for Calls

本文关键字:返回 调用 时间 函数 任何      更新时间:2023-10-16

我正在寻找一个时间函数,它保证为不同的调用返回不同的值。我在 LINUX 上尝试了以下方法,只是发现它不是我想要的,它可能会为来自不同线程的调用返回相同的值。

   long GetTickCount()        
   {          
        struct timespec now;
        clock_gettime(MONOTONIC, &now);
        return now.tv_sec * 1000000000LL + now.tv_nsec;
   }

在 Linux 上还有其他方法可以做到这一点吗?

任何时钟的粒度都有限,这可能会导致连续调用返回相同的值。 为了解决这个问题,您需要使用全局计数器:

static long long previous_time = 0;
long long get_strictly_monotonic_time() {
    int rc;
    struct timespec tp;
    long long t;
    rc = clock_gettime(CLOCK_MONOTONIC, &tp);
    if(rc < 0) return -1;
    t = tp.tv_sec * 1000000000LL + tp.tv_nsec;
    /* Critical region */
    if(t <= previous_time)
        t = previous_time + 1;
    previous_time = t;
    /* End of critical region */
    return t;
}

由于您希望这在多个线程中是可靠的,因此您需要使用全局互斥锁(上面带有"关键区域"注释的区域)保护全局计数器。