如何使用c获取linux中的当前时间戳(以纳秒为单位)

时间:2015-03-15 15:22:05

标签: c linux

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

问题我试着询问是否需要以纳秒为单位的时间 从时代开始说,这将是一个巨大的数字。

例如:

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

我如何在64位整数内拟合它?

1 个答案:

答案 0 :(得分:3)

CLOCK_MONOTONIC来自任意时代,它实际上因机器和Linux中的每次启动而异。您应该只使用来测量间隔,i。即

  (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年。

- 名义动物