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");
18 'Name1' => '...code1...',
19 'Name2' => '...code2...',
22 $t = timeit($count, '...other code...')
23 print "$count loops of other code took:",timestr($t),"\n";
27 The Benchmark module encapsulates a number of routines to help you
28 figure out how long it takes to execute some code.
36 Returns the current time. Example:
40 # ... your code here ...
42 $td = timediff($t1, $t0);
43 print "the code took:",timestr($td),"\n";
47 Enables or disable debugging by setting the C<$Benchmark::Debug> flag:
50 $t = timeit(10, ' 5 ** $Global ');
55 =head2 Standard Exports
57 The following routines will be exported into your namespace
58 if you use the Benchmark module:
62 =item timeit(COUNT, CODE)
64 Arguments: COUNT is the number of time to run the loop, and
65 the second is the code to run. CODE may be a string containing the code,
66 a reference to the function to run, or a reference to a hash containing
67 keys which are names and values which are more CODE specs.
69 Side-effects: prints out noise to standard out.
71 Returns: a Benchmark object.
83 =head2 Optional Exports
85 The following routines will be exported into your namespace
86 if you specifically ask that they be imported:
102 The data is stored as a list of values from the time and times
105 ($real, $user, $system, $children_user, $children_system)
107 in seconds for the whole loop (not divided by the number of rounds).
109 The timing is done using time(3) and times(3).
111 Code is executed in the caller's package.
115 $Benchmark::debug = 1;
117 The time of the null loop (a loop with the same
118 number of rounds but empty loop body) is subtracted
119 from the time of the real loop.
121 The null loop times are cached, the key being the
122 number of rounds. The caching can be controlled using
133 Benchmark inherits from no other class, except of course
138 The real time timing is done using time(2) and
139 the granularity is therefore only one second.
141 Short tests may produce negative figures because perl
142 can appear to take longer to execute the empty loop
143 than a short test; try:
147 The system time of the null loop might be slightly
148 more than the system time of the loop with the actual
149 code and therefore the difference might end up being E<lt> 0.
151 More documentation is needed :-( especially for styles and formats.
155 Jarkko Hietaniemi E<lt>F<Jarkko.Hietaniemi@hut.fi>E<gt>,
156 Tim Bunce E<lt>F<Tim.Bunce@ig.co.uk>E<gt>
158 =head1 MODIFICATION HISTORY
160 September 8th, 1994; by Tim Bunce.
164 # Purpose: benchmark running times of code.
167 # Usage - to time code snippets and print results:
169 # timethis($count, '...code...');
172 # timethis 100: 2 secs ( 0.23 usr 0.10 sys = 0.33 cpu)
175 # timethese($count, {
176 # Name1 => '...code1...',
177 # Name2 => '...code2...',
180 # Benchmark: timing 100 iterations of Name1, Name2...
181 # Name1: 2 secs ( 0.50 usr 0.00 sys = 0.50 cpu)
182 # Name2: 1 secs ( 0.48 usr 0.00 sys = 0.48 cpu)
184 # The default display style will automatically add child process
185 # values if non-zero.
188 # Usage - to time sections of your own code:
191 # $t0 = new Benchmark;
192 # ... your code here ...
193 # $t1 = new Benchmark;
194 # $td = &timediff($t1, $t0);
195 # print "the code took:",timestr($td),"\n";
197 # $t = &timeit($count, '...other code...')
198 # print "$count loops of other code took:",timestr($t),"\n";
202 # The data is stored as a list of values from the time and times
203 # functions: ($real, $user, $system, $children_user, $children_system)
204 # in seconds for the whole loop (not divided by the number of rounds).
207 # The timing is done using time(3) and times(3).
209 # Code is executed in the callers package
211 # Enable debugging by: $Benchmark::debug = 1;
213 # The time of the null loop (a loop with the same
214 # number of rounds but empty loop body) is substracted
215 # from the time of the real loop.
217 # The null loop times are cached, the key being the
218 # number of rounds. The caching can be controlled using
219 # &clearcache($key); &clearallcache;
220 # &disablecache; &enablecache;
224 # The real time timing is done using time(2) and
225 # the granularity is therefore only one second.
227 # Short tests may produce negative figures because perl
228 # can appear to take longer to execute the empty loop
229 # than a short test: try timethis(100,'1');
231 # The system time of the null loop might be slightly
232 # more than the system time of the loop with the actual
233 # code and therefore the difference might end up being < 0
235 # More documentation is needed :-(
236 # Especially for styles and formats.
238 # Authors: Jarkko Hietaniemi <Jarkko.Hietaniemi@hut.fi>
239 # Tim Bunce <Tim.Bunce@ig.co.uk>
242 # Last updated: Sept 8th 94 by Tim Bunce
248 @EXPORT=qw(timeit timethis timethese timediff timestr);
249 @EXPORT_OK=qw(clearcache clearallcache disablecache enablecache);
257 $defaultfmt = '5.2f';
258 $defaultstyle = 'auto';
259 # The cache can cause a slight loss of sys time accuracy. If a
260 # user does many tests (>10) with *very* large counts (>10000)
261 # or works on a very slow machine the cache may be useful.
266 sub clearcache { delete $cache{$_[0]}; }
267 sub clearallcache { %cache = (); }
268 sub enablecache { $cache = 1; }
269 sub disablecache { $cache = 0; }
272 # --- Functions to process the 'time' data type
274 sub new { my(@t)=(time, times); print "new=@t\n" if $debug; bless \@t; }
276 sub cpu_p { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $pu+$ps ; }
277 sub cpu_c { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $cu+$cs ; }
278 sub cpu_a { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $pu+$ps+$cu+$cs ; }
279 sub real { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $r ; }
284 for($i=0; $i < @$a; ++$i){
285 push(@r, $a->[$i] - $b->[$i]);
291 my($tr, $style, $f) = @_;
293 warn "bad time value" unless @t==5;
294 my($r, $pu, $ps, $cu, $cs) = @t;
295 my($pt, $ct, $t) = ($tr->cpu_p, $tr->cpu_c, $tr->cpu_a);
296 $f = $defaultfmt unless $f;
297 # format a time in the required style, other formats may be added here
298 $style = $defaultstyle unless $style;
299 $style = ($ct>0) ? 'all' : 'noc' if $style=~/^auto$/;
300 my($s) = "@t $style"; # default for unknown style
301 $s=sprintf("%2d secs (%$f usr %$f sys + %$f cusr %$f csys = %$f cpu)",
302 @t,$t) if $style =~ /^all$/;
303 $s=sprintf("%2d secs (%$f usr %$f sys = %$f cpu)",
304 $r,$pu,$ps,$pt) if $style =~ /^noc$/;
305 $s=sprintf("%2d secs (%$f cusr %$f csys = %$f cpu)",
306 $r,$cu,$cs,$ct) if $style =~ /^nop$/;
311 print STDERR "$msg",timestr($t),"\n" if ($debug);
315 # --- Functions implementing low-level support for timing loops
320 $n+=0; # force numeric now, so garbage won't creep into the eval
321 croak "negativ loopcount $n" if $n<0;
322 confess "Usage: runloop(number, string)" unless defined $c;
323 my($t0, $t1, $td); # before, after, difference
325 # find package of caller so we can execute code there
326 my ($curpack) = caller(0);
328 while (($pack) = caller(++$i)) {
329 last if $pack ne $curpack;
332 my $subcode = (ref $c eq 'CODE')
333 ? "sub { package $pack; my(\$_i)=$n; while (\$_i--){&\$c;} }"
334 : "sub { package $pack; my(\$_i)=$n; while (\$_i--){$c;} }";
335 my $subref = eval $subcode;
336 croak "runloop unable to compile '$c': $@\ncode: $subcode\n" if $@;
337 print STDERR "runloop $n '$subcode'\n" if ($debug);
342 $td = &timediff($t1, $t0);
344 timedebug("runloop:",$td);
353 printf STDERR "timeit $n $code\n" if $debug;
355 if ($cache && exists $cache{$n}){
358 $wn = &runloop($n, '');
362 $wc = &runloop($n, $code);
364 $wd = timediff($wc, $wn);
366 timedebug("timeit: ",$wc);
367 timedebug(" - ",$wn);
368 timedebug(" = ",$wd);
374 # --- Functions implementing high-level time-then-print utilities
377 my($n, $code, $title, $style) = @_;
378 my($t) = timeit($n, $code);
380 $title = "timethis $n" unless $title;
381 $style = "" unless $style;
382 printf("%10s: ", $title);
383 print timestr($t, $style),"\n";
384 # A conservative warning to spot very silly tests.
385 # Don't assume that your benchmark is ok simply because
386 # you don't get this warning!
387 print " (warning: too few iterations for a reliable count)\n"
389 || ($t->real < 1 && $n < 1000)
390 || $t->cpu_a < $min_cpu);
396 my($n, $alt, $style) = @_;
397 die "usage: timethese(count, { 'Name1'=>'code1', ... }\n"
398 unless ref $alt eq HASH;
400 my(@names) = sort keys %$alt;
401 $style = "" unless $style;
402 print "Benchmark: timing $n iterations of ",join(', ',@names),"...\n";
404 $t = timethis($n, $alt->{$_}, $_, $style);
407 # we could produce a summary from @all here
408 # sum, min, max, avg etc etc