【问题标题】:How to make clock_gettime using CLOCK_REALTIME monotonic?如何使用 CLOCK_REALTIME 单调制作clock_gettime?
【发布时间】:2014-06-11 15:30:12
【问题描述】:

CLOCK_REALTIME 的一个问题是它不是单调的,如果发生 NTP 同步,时间可能会倒退。

执行以下操作使其单调是否安全?

struct timespec GetMonotonicTime()
{
    static struct timespec last = timespec();
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    last.tv_nsec = (last.tv_sec == ts.tv_sec) ? std::max(last.tv_nsec, ts.tv_nsec) : ts.tv_nsec;
    last.tv_sec = std::max(last.tv_sec, ts.tv_sec);

    return last;
}

【问题讨论】:

标签: c++ linux time


【解决方案1】:

除了在多线程环境中运行时遇到问题之外,您的ns 属性将随着时间的推移逐渐变为 999999999。

Linux 提供CLOCK_MONOTONIC,如果这恰好是您的平台(它会满足您的需求)。

【讨论】:

  • 如果我使用 gcc __thread 关键字将最后一个变量设为线程本地,我也许可以使它成为线程安全的。你对 ns 属性确实是正确的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-19
  • 1970-01-01
  • 2011-10-13
  • 1970-01-01
相关资源
最近更新 更多