Har*_*yan 6 perl time nanotime
我想在 Perl 中获取以纳秒为单位的系统时间。我尝试了Time::HiRes
模块,它只支持微秒。
Time ::HiRes模块最多支持微秒。正如 @MarcoS 在今天的通用硬件中回答的那样,使用软件计算的纳秒精度是无意义的。
两个后续调用,获取当前微秒并随后打印
perl -MTime::HiRes=time -E '$t1=time; $t2=time; printf "%.6f\n", $_ for($t1, $t2)'
Run Code Online (Sandbox Code Playgroud)
结果(在我的系统上)
1411630025.846065
1411630025.846069
Run Code Online (Sandbox Code Playgroud)
例如,只获取当前时间两次,中间没有花费 3-4 微秒。
如果您想要一些“纳秒数字”,只需以 9 位精度打印时间,例如:
perl -MTime::HiRes=time -E '$t1=time;$t2=time; printf "%.9f\n", $_ for($t1, $t2)'
Run Code Online (Sandbox Code Playgroud)
你会得到这样的结果:
1411630910.582282066
1411630910.582283974
Run Code Online (Sandbox Code Playgroud)
相当纳秒的时间;)
不管怎样,你可以以合理的纳秒精度睡觉。来自文档
纳秒睡眠($纳秒)
休眠指定的纳秒数(1e9 秒)。返回实际睡眠的纳秒数(仅精确到微秒,最接近的千分之一)。
Run Code Online (Sandbox Code Playgroud)...
不要期望 nanosleep() 精确到一纳秒。达到一千纳秒的精度就很好了。
Perl 使用 Time::HiRes获取时间
c:\Code>perl -MDateTime::HiRes -E "while (1) {say DateTime::HiRes->now()->strftime('%F %T.%N');}"
Run Code Online (Sandbox Code Playgroud)
或者
use Time::HiRes qw(time);
use POSIX qw(strftime);
my $t = time;
my $date = strftime "%F %T.%N", localtime $t;
$date .= sprintf ".%03d", ($t-int($t))*1000; # without rounding
print $date, "\n";
Run Code Online (Sandbox Code Playgroud)