Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get system time in nano seconds in Perl?

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

like image 456
Hariprasath Sankaraiyan Avatar asked Dec 19 '22 11:12

Hariprasath Sankaraiyan


1 Answers

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)'

results (on my system)

1411630025.846065
1411630025.846069

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

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)'

you will get like:

1411630910.582282066
1411630910.582283974

pretty nanosecond times ;)

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

nanosleep ( $nanoseconds )

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

...

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

like image 104
jm666 Avatar answered Jan 08 '23 12:01

jm666