How to use high-resolution gettimeofday in Perl

In some cases, you may need to measure time in high-resolution, for example, microsecond resolution as provided by gettimeofday() system call. In order to use microsecond-resolution time in Perl, you can use Time::HiRes Perl module which provides gettimeofday() microsecond-resolution timer function.

To install Time::HiRes on Linux, run the following.

$ sudo perl -MCPAN -e ‘install Time::HiRes’

You can measure elapsed time in microsecond resolution as follows.

#/usr/bin/perl
 
use Time::HiRes qw( usleep ualarm gettimeofday tv_interval );
 
my $t0 = [gettimeofday];
[add some computation intensive routine]
my $elapsed = tv_interval ( $t0, [gettimeofday]);
 
# Or you can get second/microsecond components separately, by using:
my ($seconds, $microseconds) = gettimeofday; // current time

Subscribe to Xmodulo

Do you want to receive Linux FAQs, detailed tutorials and tips published at Xmodulo? Enter your email address below, and we will deliver our Linux posts straight to your email box, for free. Delivery powered by Google Feedburner.


Support Xmodulo

Did you find this tutorial helpful? Then please be generous and support Xmodulo!

The following two tabs change content below.
Dan Nanni is the founder and also a regular contributor of Xmodulo.com. He is a Linux/FOSS enthusiast who loves to get his hands dirty with his Linux box. He likes to procrastinate when he is supposed to be busy and productive. When he is otherwise free, he likes to watch movies and shop for the coolest gadgets.

Leave a comment

Your email address will not be published. Required fields are marked *