Is there a better way to determine elapsed time in Perl?

Depends on what you are doing. If you want to measure wall clock time (the amount of actual time that has elapsed) you can't get much better. If you want to measure how long the computer has been doing something then you might want to look at the times function or the time command. The times function in Perl returns a list of the current accumulated time for this process in your code and the code of any modules you are using, this process in system calls, all of this process's children in user code, and all of this process's children in system calls.

#!/usr/bin/perl

use strict;
use warnings;
use Time::HiRes;

my $start_time = [Time::HiRes::gettimeofday()];
.
.
.
my ($user, $system, $child_user, $child_system) = times;
print "wall clock time was ", Time::HiRes::tv_interval($start_time), "\n",
    "user time for $$ was $user\n",
    "system time for $$ was $system\n",
    "user time for all children was $child_user\n",
    "system time for all children was $child_system\n";

The time command in UNIX is similar in function. You run a command like this

time ./script.pl

and it outputs something like this

real    0m0.692s
user    0m0.019s
sys     0m0.109s

where real is the wall clock time and user and sys are the same as user and system above.

The time command is easier for a human to use, but the times function gives you more information and is easier to fit into a computer program (plus it has the benefit of producing results while a program is still running).

Oh, I forgot to mention $^T. This variable holds the start time of the program in seconds since the epoch, so if you only care about a granularity of seconds you can just say

END { print "The program ran for ", time() - $^T, " seconds\n" }

near the top of your program.


Possibly. Depends on what you mean by "better".

If you are asking for a "better" solution in terms of functionality, then this is pretty much it.

If you are asking for a "better" in the sense of "less awkward" notation, then know that, in scalar context, Time::HiRes::gettimeofday() will return floating seconds since epoch (with the fractional part representing microseconds), just like Time::HiRes::time() (which is a good drop-in replacement for the standard time() function.)

my $start_time = Time::HiRes::gettimeofday();
...
my $stop_time = Time::HiRes::gettimeofday();
printf("%.2f\n", $stop_time - $start_time);

or:

use Time::HiRes qw( time );

my $begin_time = time();
...
my $end_time = time();
printf("%.2f\n", $end_time - $begin_time);

Tags:

Time

Perl