在什么情况下 CLOCK_MONOTONIC 可能不可用

In what cases CLOCK_MONOTONIC might not be available

在 Java System.nanoTime()'s monotonic implementation on Linux relies on the fact that CLOCK_MONOTONIC is available on the OS. If it's not available, it falls back to gettimeofday 中,当使用 nanoTime 测量间隔时,可能会导致获得负时间间隔。例如,以下测试可能会失败。

long t1 = System.nanoTime();
long t2 = System.nanoTime();
assert t2 >= t1

在什么情况下 CLOCK_MONOTONIC 可能无法在服务器上使用?假设 CLOCK_MONOTONIC 时钟在所有现代 Linux 服务器上可用是否合理?

Is it reasonable to assume that CLOCK_MONOTONIC clock is available on all modern Linux servers?

我只能评论这个问题。是的,您使用的所有生产级系统都有一个 Linux 知道如何访问的单调时钟是合理的。虚拟和容器服务器也是如此。

良好的工程设计要求您对此进行检查并在假设被打破时出错,但我会在设计时指望这一点。

Is it reasonable to assume that CLOCK_MONOTONIC clock is available on all modern Linux servers?

是的。假设是合理的。

从gettime manual entry的写法来看,真正老版本的glibc是不支持CLOCK_MONOTONIC的。 (我仍在尝试弄清楚有多旧......但可能是在 glibc 声称 POSIX 1003.1 合规性时。)

CLOCK_MONOTONIC(至少)在 IEEE 标准 1003.1,2004 版中指定,尽管兼容的 libc 实现仍然可能不支持 CLOCK_MONOTONIC

Linux 内核源代码至少从 Linux 3.0 (2011) 开始支持 CLOCK_MONOTONIC 时钟。

从其他来源来看,这还取决于您系统的 glibc 是如何构建的。 (当使用“模拟计时器”构建时,不支持 CLOCK_MONOTONIC。)

以下是一些不支持的情况:


也有可能支持CLOCK_MONOTONIC但有bug:

  • Linux clock_gettime(CLOCK_MONOTONIC) strange non-monotonic behavior