【问题标题】:How do you get clock_gettime(2) clock in shell?你如何在 shell 中获取 clock_gettime(2) 时钟?
【发布时间】:2013-08-31 16:18:47
【问题描述】:

我没有看到 date 有这样的选项

/proc/uptime 是基于引导的,而不是单调的。

最后我发现 cat /proc/timer_list | grep now 产生的 nsecs 数是通过 ktime_get 获得的,如果我理解正确,它会返回单调时间,但这很麻烦。

更新:返回值必须与clock_gettime返回的值一致

【问题讨论】:

  • 您需要什么精度?
  • 那么/proc/uptime 不是单调的吗?这是一个错误吗?
  • 对不起,我真的不明白为什么正常运行时间不是单调的。
  • 不相关。我会阅读单调的定义。
  • 看来你连自己想要什么都不知道。至于我们,我们甚至不知道您为什么需要这个值。我什至不确定你是否了解自己。

标签: linux time


【解决方案1】:

看起来它在 python 3.3 中可用:http://www.python.org/dev/peps/pep-0418/

如果做不到这一点,你可以编写一个小 C 程序,调用 clock_gettime:http://linux.die.net/man/3/clock_gettime

【讨论】:

  • 这就是我不想要的。必须有一个标准的方法来做到这一点,如果没有,我宁愿修补 coreutils。
  • 很公平。除了你已经找到的/proc/timer_list,我在 shell 中找不到任何可用的东西。
  • 请注意 man 参考没有更新,现在我们有不受 ntp 更改影响的 CLOCK_MONOTONIC_RAW。
【解决方案2】:

这不回答当前的问题,而是回答原来的问题。因此,它被保留下来,因为到目前为止它对某些人有用。

在 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.

【讨论】:

  • 请你,谁投反对票,添加评论?也许我可以纠正我的错误并为自己改进 stackoverflow。
  • 这仅给出自纪元以来的秒数。
  • 据我所知,这个单调的定义是有缺陷的,因为它不一定是经过的挂钟。它甚至不需要在几秒钟内完成。
  • man clock_gettime 确实说“表示从某个未指定的起点开始的时间”。但是 linux 的起点始终是系统的启动(我不知道任何其他可能的起点)
  • "这仅给出自纪元以来的秒数。"。负数:这给出了自纪元以来的纳秒数。
【解决方案3】:

咨询/proc/uptime只有每次都写完整行才比较麻烦。为什么不这样总结:

$ alias now="awk '/^now/ {print \$3; exit}' /proc/timer_list"
$ now
396751009584948

这也避免了 cat 的无用使用。

【讨论】:

  • 是的。这很麻烦。
  • 考虑到系统调用开销,它并不比二进制调用clock_gettime(2) 差多少。从编程的角度来看,这是一个获取所需信息的单字命令。没看到麻烦,抱歉。
  • 这里的答案中,这是真正回答了我的问题的答案。谢谢!
  • 如果你想要几秒钟的小改进:awk '/^now/ {print substr($3, 1, length($3) - 9); exit}' /proc/timer_list
  • 不幸的是,这需要root:-r-------- 1 root root 0 ... /proc/timer_list
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 2011-02-17
  • 1970-01-01
  • 2012-07-04
  • 2013-07-16
  • 2013-04-22
  • 1970-01-01
相关资源
最近更新 更多