这不回答当前的问题,而是回答原来的问题。因此,它被保留下来,因为到目前为止它对某些人有用。
在 shell 中你可以只使用 date 实用程序:
date +%s.%N
date +%s%N
nanoseconds_since_70=$(date +%s%N)
从人日期:
%s seconds since 1970-01-01 00:00:00 UTC
%N nanoseconds (000000000..999999999)
纳秒部分以正确的方式补充秒数:当 %N 从 999999999 变为 0 时,%s 增加一秒。我没有这方面的参考(如果你能找到它,请编辑),但可以工作。
日期实用程序 x clock_gettime
请注意,数字不受时区变化的影响,但会受到系统时钟变化的影响,如系统管理员所做的更改、NTP 和 adjtime 功能。但是clock_gettime函数中的CLOCK_MONOTONIC也会受到影响,除了管理员的改动。
CLOCK_MONOTONIC -- Clock that cannot be set and represents monotonic time
since some unspecified starting point. This clock is not affected by
discontinuous jumps in the system time (e.g., if the system administrator
manually changes the clock), but is affected by the incremental adjustments
performed by adjtime(3) and NTP.
较新的系统有更好的解决方案:CLOCK_MONOTIC_RAW。尽管如此,这是一个按要求提供的 shell 解决方案。
了解更多
Monotonic function in Wikipedia
@caf 用户来自Difference between CLOCK_REALTIME and CLOCK_MONOTONIC? 的回答:
CLOCK_MONOTONIC represents the absolute elapsed wall-clock time since some
arbitrary, fixed point in the past. It isn't affected by changes in the
system time-of-day clock.
If you want to compute the elapsed time between two events observed on the one
machine without an intervening reboot, CLOCK_MONOTONIC is the best option.