Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get time in milliseconds without an installing an extra package?

How can I get the time in milliseconds in Perl without installing any extra package?

I am running Linux.

like image 875
JJ Liu Avatar asked Nov 03 '11 15:11

JJ Liu


People also ask

How do I get milliseconds in Linux?

date +"%T. %6N" returns the current time with nanoseconds rounded to the first 6 digits, which is microseconds. date +"%T. %3N" returns the current time with nanoseconds rounded to the first 3 digits, which is milliseconds.

How do I get milliseconds Perl?

In Perl if you want to calculate time in milliseconds (thousandths of a second) you can use Time::HiRes and the time() function.


1 Answers

Time::HiRes has been part of the core since Perl 5.7.3. To check for its availability, check for the Perl version, perl -v, or try to use it with perl -e 'use Time::HiRes;', both from the command line.

Sample usage:

use Time::HiRes qw/ time sleep /;

my $start = time;
sleep rand(10)/3;
my $end   = time;

print 'Slept for ', ( $end - $start ) , "\n";

To build on Konerak's comment, if it isn't there or it cannot be used, use native Linux commands via backticks:

sub time_since_epoch { return `date +%s.%N` }

print time_since_epoch;
like image 147
Zaid Avatar answered Oct 04 '22 03:10

Zaid