Linux bash 时间命令有多准确?
How accurate is the Linux bash time command?
我想在 bash 脚本的日志文件中为某些事件添加时间戳。我需要这个时间戳尽可能准确。我看到从 bash 执行此操作的标准方法似乎是 time
命令,它可以使用 +%s%N
选项生成纳秒时间戳。
然而,当我从 C 执行此操作时,我记得多个计时功能有多个时钟源,并且并非所有时钟源都同样准确或具有相同的保证(例如单调)。我怎么知道 time
使用什么时钟源?
man 1 time比较清楚:
These statistics consist of (i) the elapsed real time between
invocation and termination, (ii) the user CPU time (the sum of the tms_utime and tms_cutime values in a struct tms as returned by
times(2)), and (iii) the system CPU time (the sum of the tms_stime and tms_cstime values in a struct tms as returned by
times(2)).
所以我们可以去 man 3p times where is just states The accuracy of the times reported is intentionally left unspecified to allow implementations flexibility in design, from uniprocessor to multi-processor networks.
So we can go to man 2 times,了解到它都是用 clock_t
测量的,也许我们应该用 clock_gettime
而不是
How do I know what clock source time uses?
与通常在 GNU 系统上一样,所有程序都是开源的。所以你去下载内核的源代码,你 shell 并检查它们以了解它是如何工作的。我在 bash time_command() there are many methods available and nowadays bash uses rusage 中看到 times
.
的替代品
How accurate is the Linux bash time command?
getrusage()
和times()
都是system calls by themselfs,所以这些值直接从内核返回。我的猜测是,它们是用内核可以给我们的精度来测量的——所以用 jiffies/HZ
.
测量的 分辨率 将等于 jiffies,所以如果我的数学正确的话,通常 300 HZ 就是 3.333ms。 准确度 将取决于您的硬件,也可能是工作量 - 我高估的猜测是这些值将达到一或两个 jiffies 的准确度,因此最多约 7 毫秒。
我想在 bash 脚本的日志文件中为某些事件添加时间戳。我需要这个时间戳尽可能准确。我看到从 bash 执行此操作的标准方法似乎是 time
命令,它可以使用 +%s%N
选项生成纳秒时间戳。
然而,当我从 C 执行此操作时,我记得多个计时功能有多个时钟源,并且并非所有时钟源都同样准确或具有相同的保证(例如单调)。我怎么知道 time
使用什么时钟源?
man 1 time比较清楚:
These statistics consist of (i) the elapsed real time between invocation and termination, (ii) the user CPU time (the sum of the tms_utime and tms_cutime values in a struct tms as returned by times(2)), and (iii) the system CPU time (the sum of the tms_stime and tms_cstime values in a struct tms as returned by times(2)).
所以我们可以去 man 3p times where is just states The accuracy of the times reported is intentionally left unspecified to allow implementations flexibility in design, from uniprocessor to multi-processor networks.
So we can go to man 2 times,了解到它都是用 clock_t
测量的,也许我们应该用 clock_gettime
而不是
How do I know what clock source time uses?
与通常在 GNU 系统上一样,所有程序都是开源的。所以你去下载内核的源代码,你 shell 并检查它们以了解它是如何工作的。我在 bash time_command() there are many methods available and nowadays bash uses rusage 中看到 times
.
How accurate is the Linux bash time command?
getrusage()
和times()
都是system calls by themselfs,所以这些值直接从内核返回。我的猜测是,它们是用内核可以给我们的精度来测量的——所以用 jiffies/HZ
.
测量的 分辨率 将等于 jiffies,所以如果我的数学正确的话,通常 300 HZ 就是 3.333ms。 准确度 将取决于您的硬件,也可能是工作量 - 我高估的猜测是这些值将达到一或两个 jiffies 的准确度,因此最多约 7 毫秒。