问题描述
我想从 bash 脚本为日志文件中的某些事件添加时间戳.我需要这个时间戳尽可能准确.我看到从 bash 执行此操作的标准方法似乎是 time
命令,它可以使用 +%s%N
选项生成纳秒时间戳.
I want to timestamp some events in a logfile from a bash script. I need this timestamp to be as accurate as possible. I see that the standard way of doing this from bash seems to be the time
command, which can produce a nanoseconds timestamp with the +%s%N
option.
然而,在从 C 中执行此操作时,我记得多个计时函数具有多个时钟源,并且并非所有这些函数都同样准确或具有相同的保证(例如,是单调的).我如何知道 time
使用的时钟源是什么?
However, when doing this from C I remembered that multiple timekeeping functions had multiple clock sources, and not all of them were equally accurate or had the same guarantees (e.g. being monotonic). How do I know what clock source time
uses?
推荐答案
man 1 次 相当清楚:
这些统计数据包括 (i) 之间经过的实时时间调用和终止,(ii) 用户 CPU 时间(结构 tms 中的 tms_utime 和 tms_cutime 值的总和,由times(2)),以及 (iii) 系统 CPU 时间(结构 tms 中的 tms_stime 和 tms_cstime 值的总和,由次(2)).
所以我们可以去man 3p times只是声明 有意不指定报告时间的准确性,以允许从单处理器到多处理器网络的设计实现灵活性.
所以我们可以去 man 2 次,并了解到这一切都是用 clock_t
测量的,也许我们应该使用 clock_gettime
代替
通常在 GNU 系统上,所有程序都是开源的.所以你去下载内核的源代码,然后对它们进行 shell 和检查,看看它是如何工作的.我在 bash time_command() 中看到有很多方法可用现在 bash 使用 rusage 作为 .
As usually on a GNU system, all programs are open source. So you go and download sources of the kernel and you shell and inspect them to see how it works. I see in bash time_command() there are many methods available and nowadays bash uses rusage as a replacement for times
.
Linux bash 时间命令有多准确?
getrusage()
和 times()
都是 自己的系统调用,因此这些值直接从内核返回.我的猜测是它们是用内核可以给我们的精度来衡量的——所以用 jiffies/HZ
.
Both getrusage()
and times()
are system calls by themselfs, so the values are returned straight from the kernel. My guess would be that they are measured with the accuracy the kernel can give us - so with jiffies/HZ
.
测量的分辨率将等于 jiffies,因此如果我的数学正确,通常使用 300 HZ 即 3.333 毫秒.准确度将取决于您的硬件,也可能取决于工作负载 - 我高估的猜测是这些值将达到一两个 jiffies 的准确度,因此最高约为 7 毫秒.
The resolution of the measurement will be equal to jiffies, so usually with 300 HZ thats 3.333ms if my math is right. The accuracy will depend on your hardware, maybe also workload - my overestimated guess would be that the values will be right up to one or two jiffies of accuracy, so up to ~7 milliseconds.
这篇关于Linux bash time 命令的准确度如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!