Entry
How can I measure the relative performance of two slightly different Perl scripts?
Jul 16th, 2002 14:58
Jack Nerad, Per M Knutsen, http://members.home.net/andrew-johnson/perl/archit/msg00018.html
There are three ways to do it:
1. With the built-in 'times' function which returns the user and system
times of the current process (in seconds). For example,
#!/usr/bin/perl -w
my $count = 100000;
my $start = (times)[0];
for (my $i = 0; $i ‹ $count; $i++){
$_ = 'foobar';
s/[aeiou]//g;
#tr/aeiou//d;
}
print "** $_ **\\n"; # just to test result of operation
my $delta = (times)[0] - $start;
print "Took $delta seconds on $count iterations\\n";
2. The other main method of benchmarking is to use the Benchmark.pm
module included with your perl distribution. For example,
#!/usr/bin/perl -w
use Benchmark;
my $count = 100000;
timethese($count, {
cntrl =› sub {$_ = 'foobar'},
subst =› sub {$_ = 'foobar'; s/[aeiou]//g},
trans =› sub {$_ = 'foobar'; tr/aeiou//d},
});
For a more thorough explanation of these examples, read Andrew
Johnson's article 'Perl Benchmarking': http://members.home.net/andrew-
johnson/perl/archit/msg00018.html
3. If you are working on a Unix machine, you can use the "time" command
to see how long it takes to run an entire script.
$ time program1
real
0m0.419s
user
0m0.420s
sys
0m0.000s
$ time program2
real
0m0.834s
user
0m0.830s
sys
0m0.000s
See the time(1) manual pages for your system for further details about
the time command.