Generally used to compare the running times of various code fragments:
use Benchmark qw(:all) ; timethis ($count, "code"); # Use Perl code in strings... timethese($count, { 'Name1' => '...code1...', 'Name2' => '...code2...', }); # ... or use subroutine references. timethese($count, { 'Name1' => sub { ...code1... }, 'Name2' => sub { ...code2... }, }); # cmpthese can be used both ways as well cmpthese($count, { 'Name1' => '...code1...', 'Name2' => '...code2...', }); cmpthese($count, { 'Name1' => sub { ...code1... }, 'Name2' => sub { ...code2... }, }); # ...or in two stages $results = timethese($count, { 'Name1' => sub { ...code1... }, 'Name2' => sub { ...code2... }, }, 'none' ); cmpthese( $results ) ;
Returns results like this:
Benchmark: running fishbot, merlyn, ovid for at least 3 CPU seconds... fishbot: 3 wallclock secs ( 3.17 usr + 0.03 sys = 3.20 CPU) @ 7980.96/s (n=25571) merlyn: 3 wallclock secs ( 3.21 usr + 0.03 sys = 3.23 CPU) @ 9209.27/s (n=29792) ovid: 3 wallclock secs ( 3.10 usr + 0.04 sys = 3.14 CPU) @ 22007.97/s (n=68995)
Giving a negative count = CPU |count| seconds. Count = 0 means 3 seconds (the minimum).
Returns results like this:
Rate fishbot merlyn ovid fishbot 14265/s -- -15% -55% merlyn 16812/s 18% -- -47% ovid 31496/s 121% 87% --
You can also feed the result of a timethese into a cmpthese.
You can also insert this into a larger program to give the running time of a sub-segment:
use Benchmark; $t0 = new Benchmark; # ... your code here ... $t1 = new Benchmark; $td = timediff($t1, $t0); print "the code took:",timestr($td),"\n";