【问题标题】:How to get current timestamp in nanoseconds in linux using c如何使用c在linux中以纳秒为单位获取当前时间戳
【发布时间】:2015-09-10 14:57:31
【问题描述】:

我知道我们可以使用clock_gettime(CLOCK_MONOTONIC)

我尝试问的问题是,如果我需要以纳秒为单位的时间 从纪元说,这将是一个巨大的数字。

例如:

  • 自纪元以来的秒数是13438461673 所以13438461673 * 1000000000

如何将其放入 64 位整数中?

【问题讨论】:

  • 您真正的问题是如何存储大于 64 位的整数?
  • ,而是使用例如一个timespec 结构,类似于clock_gettime 填充的结构。
  • 所以你可能想在这里阅读:stackoverflow.com/questions/15601430/…
  • 那么你有冲突的要求,你应该与某人提出这个问题。
  • @NominalAnimal 是的,我的错误。我以为 time_t 很长(64 位).. 看来我打错了灌木丛..

标签: c linux


【解决方案1】:

CLOCK_MONOTONIC 来自 arbitrary 时代,它实际上因机器和 Linux 中的每次启动而异。您应该仅将其用于测量间隔,即。 e.

  (int64_t)(after.tv_sec - before.tv_sec) * (int64_t)1000000000UL
+ (int64_t)(after.tv_nsec - before.tv_nsec)

。对于时间戳,请使用 CLOCK_REALTIME,因为它使用 1970-01-01 00:00:00 UTC 纪元。 int64_t 可以处理 CLOCK_REALTIME 纳秒精度的时间戳 –

(int64_t)(t.tv_sec) * (int64_t)1000000000 + (int64_t)(t.tv_nsec)

–,至少从 1679 年到 2261 年;范围是 ±292 年,而不是 ±145 年。

– 标称动物

【讨论】:

    猜你喜欢
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 2015-07-12
    相关资源
    最近更新 更多