5 Benchmark - benchmark running times of code
7 timethis - run a chunk of code several times
9 timethese - run several chunks of code several times
11 timeit - run a chunk of code and see how long it goes
15 timethis ($count, "code");
17 # Use Perl code in strings...
19 'Name1' => '...code1...',
20 'Name2' => '...code2...',
23 # ... or use subroutine references.
25 'Name1' => sub { ...code1... },
26 'Name2' => sub { ...code2... },
29 $t = timeit($count, '...other code...')
30 print "$count loops of other code took:",timestr($t),"\n";
34 The Benchmark module encapsulates a number of routines to help you
35 figure out how long it takes to execute some code.
43 Returns the current time. Example:
47 # ... your code here ...
49 $td = timediff($t1, $t0);
50 print "the code took:",timestr($td),"\n";
54 Enables or disable debugging by setting the C<$Benchmark::Debug> flag:
57 $t = timeit(10, ' 5 ** $Global ');
62 =head2 Standard Exports
64 The following routines will be exported into your namespace
65 if you use the Benchmark module:
69 =item timeit(COUNT, CODE)
71 Arguments: COUNT is the number of times to run the loop, and CODE is
72 the code to run. CODE may be either a code reference or a string to
73 be eval'd; either way it will be run in the caller's package.
75 Returns: a Benchmark object.
77 =item timethis ( COUNT, CODE, [ TITLE, [ STYLE ]] )
79 Time COUNT iterations of CODE. CODE may be a string to eval or a
80 code reference; either way the CODE will run in the caller's package.
81 Results will be printed to STDOUT as TITLE followed by the times.
82 TITLE defaults to "timethis COUNT" if none is provided. STYLE
83 determines the format of the output, as described for timestr() below.
85 The COUNT can be zero or negative: this means the I<minimum number of
86 CPU seconds> to run. A zero signifies the default of 3 seconds. For
87 example to run at least for 10 seconds:
91 or to run two pieces of code tests for at least 3 seconds:
93 timethese(0, { test1 => '...', test2 => '...'})
95 CPU seconds is, in UNIX terms, the user time plus the system time of
96 the process itself, as opposed to the real (wallclock) time and the
97 time spent by the child processes. Less than 0.1 seconds is not
98 accepted (-0.01 as the count, for example, will cause a fatal runtime
101 Note that the CPU seconds is the B<minimum> time: CPU scheduling and
102 other operating system factors may complicate the attempt so that a
103 little bit more time is spent. The benchmark output will, however,
104 also tell the number of C<$code> runs/second, which should be a more
105 interesting number than the actually spent seconds.
107 Returns a Benchmark object.
109 =item timethese ( COUNT, CODEHASHREF, [ STYLE ] )
111 The CODEHASHREF is a reference to a hash containing names as keys
112 and either a string to eval or a code reference for each value.
113 For each (KEY, VALUE) pair in the CODEHASHREF, this routine will
116 timethis(COUNT, VALUE, KEY, STYLE)
118 The routines are called in string comparison order of KEY.
120 The COUNT can be zero or negative, see timethis().
122 =item timediff ( T1, T2 )
124 Returns the difference between two Benchmark times as a Benchmark
125 object suitable for passing to timestr().
127 =item timestr ( TIMEDIFF, [ STYLE, [ FORMAT ] ] )
129 Returns a string that formats the times in the TIMEDIFF object in
130 the requested STYLE. TIMEDIFF is expected to be a Benchmark object
131 similar to that returned by timediff().
133 STYLE can be any of 'all', 'noc', 'nop' or 'auto'. 'all' shows each
134 of the 5 times available ('wallclock' time, user time, system time,
135 user time of children, and system time of children). 'noc' shows all
136 except the two children times. 'nop' shows only wallclock and the
137 two children times. 'auto' (the default) will act as 'all' unless
138 the children times are both zero, in which case it acts as 'noc'.
140 FORMAT is the L<printf(3)>-style format specifier (without the
141 leading '%') to use to print the times. It defaults to '5.2f'.
145 =head2 Optional Exports
147 The following routines will be exported into your namespace
148 if you specifically ask that they be imported:
152 =item clearcache ( COUNT )
154 Clear the cached time for COUNT rounds of the null loop.
156 =item clearallcache ( )
158 Clear all cached times.
160 =item disablecache ( )
162 Disable caching of timings for the null loop. This will force Benchmark
163 to recalculate these timings for each new piece of code timed.
165 =item enablecache ( )
167 Enable caching of timings for the null loop. The time taken for COUNT
168 rounds of the null loop will be calculated only once for each
169 different COUNT used.
175 The data is stored as a list of values from the time and times
178 ($real, $user, $system, $children_user, $children_system)
180 in seconds for the whole loop (not divided by the number of rounds).
182 The timing is done using time(3) and times(3).
184 Code is executed in the caller's package.
186 The time of the null loop (a loop with the same
187 number of rounds but empty loop body) is subtracted
188 from the time of the real loop.
190 The null loop times are cached, the key being the
191 number of rounds. The caching can be controlled using
202 Benchmark inherits from no other class, except of course
207 Comparing eval'd strings with code references will give you
208 inaccurate results: a code reference will show a slower
209 execution time than the equivalent eval'd string.
211 The real time timing is done using time(2) and
212 the granularity is therefore only one second.
214 Short tests may produce negative figures because perl
215 can appear to take longer to execute the empty loop
216 than a short test; try:
220 The system time of the null loop might be slightly
221 more than the system time of the loop with the actual
222 code and therefore the difference might end up being E<lt> 0.
226 Jarkko Hietaniemi <F<jhi@iki.fi>>, Tim Bunce <F<Tim.Bunce@ig.co.uk>>
228 =head1 MODIFICATION HISTORY
230 September 8th, 1994; by Tim Bunce.
232 March 28th, 1997; by Hugo van der Sanden: added support for code
233 references and the already documented 'debug' method; revamped
236 April 04-07th, 1997: by Jarkko Hietaniemi, added the run-for-some-time
241 # evaluate something in a clean lexical environment
242 sub _doeval { eval shift }
245 # put any lexicals at file scope AFTER here
251 @EXPORT=qw(timeit timethis timethese timediff timestr);
252 @EXPORT_OK=qw(clearcache clearallcache disablecache enablecache);
260 $defaultfmt = '5.2f';
261 $defaultstyle = 'auto';
262 # The cache can cause a slight loss of sys time accuracy. If a
263 # user does many tests (>10) with *very* large counts (>10000)
264 # or works on a very slow machine the cache may be useful.
269 sub debug { $debug = ($_[1] != 0); }
271 sub clearcache { delete $cache{$_[0]}; }
272 sub clearallcache { %cache = (); }
273 sub enablecache { $cache = 1; }
274 sub disablecache { $cache = 0; }
276 # --- Functions to process the 'time' data type
278 sub new { my @t = (time, times, @_ == 2 ? $_[1] : 0);
279 print "new=@t\n" if $debug;
282 sub cpu_p { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $pu+$ps ; }
283 sub cpu_c { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $cu+$cs ; }
284 sub cpu_a { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $pu+$ps+$cu+$cs ; }
285 sub real { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $r ; }
290 for (my $i=0; $i < @$a; ++$i) {
291 push(@r, $a->[$i] - $b->[$i]);
297 my($tr, $style, $f) = @_;
299 warn "bad time value (@t)" unless @t==6;
300 my($r, $pu, $ps, $cu, $cs, $n) = @t;
301 my($pt, $ct, $t) = ($tr->cpu_p, $tr->cpu_c, $tr->cpu_a);
302 $f = $defaultfmt unless defined $f;
303 # format a time in the required style, other formats may be added here
304 $style ||= $defaultstyle;
305 $style = ($ct>0) ? 'all' : 'noc' if $style eq 'auto';
306 my $s = "@t $style"; # default for unknown style
307 $s=sprintf("%2d wallclock secs (%$f usr %$f sys + %$f cusr %$f csys = %$f CPU)",
308 @t,$t) if $style eq 'all';
309 $s=sprintf("%2d wallclock secs (%$f usr + %$f sys = %$f CPU)",
310 $r,$pu,$ps,$pt) if $style eq 'noc';
311 $s=sprintf("%2d wallclock secs (%$f cusr + %$f csys = %$f CPU)",
312 $r,$cu,$cs,$ct) if $style eq 'nop';
313 $s .= sprintf(" @ %$f/s (n=$n)", $n / ( $pu + $ps )) if $n;
319 print STDERR "$msg",timestr($t),"\n" if $debug;
322 # --- Functions implementing low-level support for timing loops
327 $n+=0; # force numeric now, so garbage won't creep into the eval
328 croak "negative loopcount $n" if $n<0;
329 confess "Usage: runloop(number, [string | coderef])" unless defined $c;
330 my($t0, $t1, $td); # before, after, difference
332 # find package of caller so we can execute code there
333 my($curpack) = caller(0);
335 while (($pack) = caller(++$i)) {
336 last if $pack ne $curpack;
339 my ($subcode, $subref);
340 if (ref $c eq 'CODE') {
341 $subcode = "sub { for (1 .. $n) { local \$_; package $pack; &\$c; } }";
342 $subref = eval $subcode;
345 $subcode = "sub { for (1 .. $n) { local \$_; package $pack; $c;} }";
346 $subref = _doeval($subcode);
348 croak "runloop unable to compile '$c': $@\ncode: $subcode\n" if $@;
349 print STDERR "runloop $n '$subcode'\n" if $debug;
351 $t0 = Benchmark->new(0);
353 $t1 = Benchmark->new($n);
354 $td = &timediff($t1, $t0);
356 timedebug("runloop:",$td);
365 printf STDERR "timeit $n $code\n" if $debug;
367 if ($cache && exists $cache{$n}) {
370 $wn = &runloop($n, '');
374 $wc = &runloop($n, $code);
376 $wd = timediff($wc, $wn);
378 timedebug("timeit: ",$wc);
379 timedebug(" - ",$wn);
380 timedebug(" = ",$wd);
390 my ($code, $tmax) = @_;
392 if ( not defined $tmax or $tmax == 0 ) {
393 $tmax = $default_for;
394 } elsif ( $tmax < 0 ) {
398 die "runfor(..., $tmax): timelimit cannot be less than $min_for.\n"
401 my ($n, $td, $tc, $ntot, $rtot, $utot, $stot, $cutot, $cstot );
403 # First find the minimum $n that gives a non-zero timing.
407 for ($n = 1, $tc = 0; $tc <= 0; $n *= 2 ) {
408 $td = timeit($n, $code);
409 $tc = $td->[1] + $td->[2];
415 my $tpra = 0.05 * $tmax; # Target/time practice.
417 # Double $n until we have think we have practiced enough.
418 for ( $n = 1; $ttot < $tpra; $n *= 2 ) {
419 $td = timeit($n, $code);
425 $ttot = $utot + $stot;
432 # Then iterate towards the $tmax.
433 while ( $ttot < $tmax ) {
434 $r = $tmax / $ttot - 1; # Linear approximation.
436 $n = $nmin if $n < $nmin;
437 $td = timeit($n, $code);
442 $ttot = $utot + $stot;
447 return bless [ $rtot, $utot, $stot, $cutot, $cstot, $ntot ];
450 # --- Functions implementing high-level time-then-print utilities
454 return $n == 0 ? $default_for : $n < 0 ? -$n : undef;
458 my($n, $code, $title, $style) = @_;
462 croak "non-integer loopcount $n, stopped" if int($n)<$n;
463 $t = timeit($n, $code);
464 $title = "timethis $n" unless defined $title;
466 $fort = n_to_for( $n );
467 $t = runfor($code, $fort);
468 $title = "timethis for $fort" unless defined $title;
472 $style = "" unless defined $style;
473 printf("%10s: ", $title);
474 print timestr($t, $style, $defaultfmt),"\n";
476 $n = $forn if defined $forn;
478 # A conservative warning to spot very silly tests.
479 # Don't assume that your benchmark is ok simply because
480 # you don't get this warning!
481 print " (warning: too few iterations for a reliable count)\n"
483 || ($t->real < 1 && $n < 1000)
484 || $t->cpu_a < $min_cpu;
489 my($n, $alt, $style) = @_;
490 die "usage: timethese(count, { 'Name1'=>'code1', ... }\n"
491 unless ref $alt eq HASH;
492 my @names = sort keys %$alt;
493 $style = "" unless defined $style;
496 croak "non-integer loopcount $n, stopped" if int($n)<$n;
497 print "timing $n iterations of";
501 print " ", join(', ',@names);
503 my $for = n_to_for( $n );
504 print ", each for at least $for CPU seconds";
508 # we could save the results in an array and produce a summary here
509 # sum, min, max, avg etc etc
510 foreach my $name (@names) {
511 timethis ($n, $alt -> {$name}, $name, $style);