5

可能重复:
Linux clock_gettime(CLOCK_MONOTONIC) 奇怪的非单调行为

在遇到 Erlang 崩溃的一些问题后,我编写了一个程序,它反复调用 clock_gettime(CLOCK_MONOTONIC, &ts) 并检查它是否会倒退,不幸的是它有时会倒退。

这是我正在使用的测试程序:

#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
    struct timespec ts_start;
    struct timespec ts_end;
    int i;

    clock_gettime(CLOCK_MONOTONIC, &ts_start);
    clock_gettime(CLOCK_MONOTONIC, &ts_end);

    for(i = 0; i<10000000; i++) {
            if(ts_end.tv_sec <= ts_start.tv_sec
               && ts_end.tv_nsec < ts_start.tv_nsec) {
                    printf("ERROR!\n");
                    return 1;
            }


            ts_start.tv_sec = ts_end.tv_sec;
            ts_start.tv_nsec = ts_end.tv_nsec;
            clock_gettime(CLOCK_MONOTONIC, &ts_end);
    }

    printf("OK\n");
    return 0;
}

在我的 Hyper-V VM(内核 2.6.18-238.12.1.e15,已尝试其他)上,它偶尔会输出 ERROR,但在物理机上它总是输出 OK。

知道为什么 CLOCK_MONOTONIC 不会是单调的吗?

4

0 回答 0