如何在 Perl 中以纳秒为单位获取系统时间?

问题描述:

我想在 Perl 中以纳秒为单位获取系统时间.我尝试了 Time::HiRes 模块,它只支持微秒.

I wanted to get system time in nano seconds in Perl. I tried Time::HiRes module and it's supporting only until micro seconds.

Time::HiRes 模块最多支持微秒.正如@MarcoS 在当今常见的硬件中回答的那样,使用软件计算的纳秒精度是无稽之谈.

The Time::HiRes module supports up to microseconds. As @MarcoS answered in the today common hardware is nonsense to use nanosecond precision counted by software.

随后的两次调用,获取当前微秒并在之后打印

Two subsequent calls, getting the current microseconds and print both afterwards

perl -MTime::HiRes=time -E '$t1=time; $t2=time; printf "%.6f\n", $_ for($t1, $t2)'

结果(在我的系统上)

1411630025.846065
1411630025.846069

例如只获取当前时间两次,没有任何花费 3-4 微秒.

e.g. only getting the current time two times and nothing between costs 3-4 microseconds.

如果您想要一些纳秒数",只需以 9 位精度打印时间,例如:

If you want some "nanosecond numbers", simply print the time with 9digit precision, like:

perl -MTime::HiRes=time -E '$t1=time;$t2=time; printf "%.9f\n", $_ for($t1, $t2)'

你会得到:

1411630910.582282066
1411630910.582283974

相当纳秒时间;)

无论如何,您可以以合理的纳秒精度睡眠.来自文档

Anyway, you can sleep with reasonable nanosecond precision. From the doc

nanosleep ( $nanoseconds )

休眠指定的纳秒数(1e9ths 秒).返回实际睡眠的纳秒数(准确仅到微秒,最接近的千位).

Sleeps for the number of nanoseconds (1e9ths of a second) specified. Returns the number of nanoseconds actually slept (accurate only to microseconds, the nearest thousand of them).

...

不要期望 nanosleep() 精确到一纳秒.甚至达到一千纳秒的精度也不错.

Do not expect nanosleep() to be exact down to one nanosecond. Getting even accuracy of one thousand nanoseconds is good.