10 use vars qw($foo $bar $baz $ballast);
11 use Test::More tests => 194;
13 use Benchmark qw(:all);
21 fib($n-1) + fib($n-2);
26 qr/(\d+) +wallclock secs? +\( *(-?\d+\.\d\d) +usr +(-?\d+\.\d\d) +sys +\+ +(-?\d+\.\d\d) +cusr +(-?\d+\.\d\d) +csys += +(-?\d+\.\d\d) +CPU\)/;
28 qr/(\d+) +wallclock secs? +\( *(-?\d+\.\d\d) +usr +\+ +(-?\d+\.\d\d) +sys += +(-?\d+\.\d\d) +CPU\)/;
30 qr/(\d+) +wallclock secs? +\( *(-?\d+\.\d\d) +cusr +\+ +(-?\d+\.\d\d) +csys += +\d+\.\d\d +CPU\)/;
31 # Please don't trust the matching parenthises to be useful in this :-)
32 my $Default_Pattern = qr/$All_Pattern|$Noc_Pattern/;
34 my $t0 = new Benchmark;
35 isa_ok ($t0, 'Benchmark', "Ensure we can create a benchmark object");
37 # We use the benchmark object once we've done some work:
39 isa_ok(timeit(5, sub {++$foo}), 'Benchmark', "timeit CODEREF");
40 is ($foo, 5, "benchmarked code was run 5 times");
42 isa_ok(timeit(5, '++$bar'), 'Benchmark', "timeit eval");
43 is ($bar, 5, "benchmarked code was run 5 times");
45 # is coderef called with spurious arguments?
46 timeit( 1, sub { $foo = @_ });
47 is ($foo, 0, "benchmarked code called without arguments");
50 print "# Burning CPU to benchmark things will take time...\n";
54 # We need to do something fairly slow in the coderef.
55 # Same coderef. Same place in memory.
56 my $coderef = sub {$baz += fib($ballast)};
58 # The default is three.
60 my $threesecs = countit(0, $coderef);
61 isa_ok($threesecs, 'Benchmark', "countit 0, CODEREF");
62 isnt ($baz, 0, "benchmarked code was run");
63 my $in_threesecs = $threesecs->iters;
64 print "# $in_threesecs iterations\n";
65 ok ($in_threesecs > 0, "iters returned positive iterations");
67 my $estimate = int (100 * $in_threesecs / 3) / 100;
68 print "# from the 3 second run estimate $estimate iterations in 1 second...\n";
70 my $onesec = countit(1, $coderef);
71 isa_ok($onesec, 'Benchmark', "countit 1, CODEREF");
72 isnt ($baz, 0, "benchmarked code was run");
73 my $in_onesec = $onesec->iters;
74 print "# $in_onesec iterations\n";
75 ok ($in_onesec > 0, "iters returned positive iterations");
78 my $difference = $in_onesec - $estimate;
79 my $actual = abs ($difference / $in_onesec);
80 ok ($actual < $delta, "is $in_onesec within $delta of estimate ($estimate)");
81 print "# $in_onesec is between " . ($delta / 2) .
82 " and $delta of estimate. Not that safe.\n" if $actual > $delta/2;
85 # I found that the eval'ed version was 3 times faster than the coderef.
86 # (now it has a different ballast value)
88 my $again = countit(1, '$baz += fib($ballast)');
89 isa_ok($onesec, 'Benchmark', "countit 1, eval");
90 isnt ($baz, 0, "benchmarked code was run");
91 my $in_again = $again->iters;
92 print "# $in_again iterations\n";
93 ok ($in_again > 0, "iters returned positive iterations");
96 my $t1 = new Benchmark;
97 isa_ok ($t1, 'Benchmark', "Create another benchmark object now we're finished");
99 my $diff = timediff ($t1, $t0);
100 isa_ok ($diff, 'Benchmark', "Get the time difference");
101 isa_ok (timesum ($t0, $t1), 'Benchmark', "check timesum");
103 my $default = timestr ($diff);
104 isnt ($default, '', 'timestr ($diff)');
105 my $auto = timestr ($diff, 'auto');
106 is ($auto, $default, 'timestr ($diff, "auto") matches timestr ($diff)');
109 my $all = timestr ($diff, 'all');
110 like ($all, $All_Pattern, 'timestr ($diff, "all")');
113 my ($wallclock, $usr, $sys, $cusr, $csys, $cpu) = $all =~ $All_Pattern;
115 is (timestr ($diff, 'none'), '', "none supresses output");
117 my $noc = timestr ($diff, 'noc');
118 like ($noc, qr/$wallclock +wallclock secs? +\( *$usr +usr +\+ +$sys +sys += +$cpu +CPU\)/, 'timestr ($diff, "noc")');
120 my $nop = timestr ($diff, 'nop');
121 like ($nop, qr/$wallclock +wallclock secs? +\( *$cusr +cusr +\+ +$csys +csys += +\d+\.\d\d +CPU\)/, 'timestr ($diff, "nop")');
124 pass ('"auto" is "noc"');
126 is ($auto, $all, '"auto" isn\'t "noc", so should be eq to "all"');
129 like (timestr ($diff, 'all', 'E'),
130 qr/(\d+) +wallclock secs? +\( *\d\.\d+E[-+]?\d\d\d? +usr +\d\.\d+E[-+]?\d\d\d? +sys +\+ +\d\.\d+E[-+]?\d\d\d? +cusr +\d\.\d+E[-+]?\d\d\d? +csys += +\d\.\d+E[-+]?\d\d\d? +CPU\)/, 'timestr ($diff, "all", "E") [sprintf format of "E"]');
133 my $out = tie *OUT, 'TieOut';
139 my $got = timethis($iterations, sub {++$foo});
141 isa_ok($got, 'Benchmark', "timethis CODEREF");
142 is ($foo, $iterations, "benchmarked code was run $iterations times");
145 like ($got, qr/^timethis $iterations/, 'default title');
146 like ($got, $Default_Pattern, 'default format is all or noc');
150 $got = timethis($iterations, '++$bar');
152 isa_ok($got, 'Benchmark', "timethis eval");
153 is ($bar, $iterations, "benchmarked code was run $iterations times");
156 like ($got, qr/^timethis $iterations/, 'default title');
157 like ($got, $Default_Pattern, 'default format is all or noc');
159 my $title = 'lies, damn lies and benchmarks';
162 $got = timethis($iterations, sub {++$foo}, $title);
164 isa_ok($got, 'Benchmark', "timethis with title");
165 is ($foo, $iterations, "benchmarked code was run $iterations times");
168 like ($got, qr/^$title:/, 'specify title');
169 like ($got, $Default_Pattern, 'default format is all or noc');
171 # default is auto, which is all or noc. nop can never match the default
174 $got = timethis($iterations, sub {++$foo}, $title, 'nop');
176 isa_ok($got, 'Benchmark', "timethis with format");
177 is ($foo, $iterations, "benchmarked code was run $iterations times");
180 like ($got, qr/^$title:/, 'specify title');
181 like ($got, $Nop_Pattern, 'specify format as nop');
187 $got = timethis(-2, sub {$foo+= fib($ballast)}, $title, 'none');
190 isa_ok($got, 'Benchmark',
191 "timethis, at least 2 seconds with format 'none'");
192 ok ($foo > 0, "benchmarked code was run");
193 ok ($end - $start > 1, "benchmarked code ran for over 1 second");
196 # Remove any warnings about having too few iterations.
197 $got =~ s/\(warning:[^\)]+\)//gs;
198 $got =~ s/^[ \t\n]+//s; # Remove all the whitespace from the beginning
200 is ($got, '', "format 'none' should suppress output");
203 $foo = $bar = $baz = 0;
205 $got = timethese($iterations, { Foo => sub {++$foo}, Bar => '++$bar',
206 Baz => sub {++$baz} });
208 is(ref ($got), 'HASH', "timethese should return a hashref");
209 isa_ok($got->{Foo}, 'Benchmark', "Foo value");
210 isa_ok($got->{Bar}, 'Benchmark', "Bar value");
211 isa_ok($got->{Baz}, 'Benchmark', "Baz value");
212 eq_set([keys %$got], [qw(Foo Bar Baz)], 'should be exactly three objects');
213 is ($foo, $iterations, "Foo code was run $iterations times");
214 is ($bar, $iterations, "Bar code was run $iterations times");
215 is ($baz, $iterations, "Baz code was run $iterations times");
218 # Remove any warnings about having too few iterations.
219 $got =~ s/\(warning:[^\)]+\)//gs;
221 like ($got, qr/timing $iterations iterations of\s+Bar\W+Baz\W+Foo\W*?\.\.\./s,
224 $got =~ s/.*\.\.\.//s;
225 like ($got, qr/\bBar\b.*\bBaz\b.*\bFoo\b/s, 'check output is in sorted order');
226 like ($got, $Default_Pattern, 'should find default format somewhere');
229 { # ensure 'use strict' does not leak from Benchmark.pm into benchmarked code
235 { undeclared_var => q{ $i++; $i-- },
236 symbolic_ref => q{ $bar = 42;
244 is( $@, '', q{no strict leakage in name => 'code'} );
248 { undeclared_var => sub { $i++; $i-- },
249 symbolic_ref => sub { $bar = 42;
256 is( $@, '', q{no strict leakage in name => sub { code }} );
263 my $code_to_test = { Foo => sub {$foo+=fib($ballast-2)},
264 Bar => sub {$bar+=fib($ballast)}};
265 # Keep these for later.
271 $results = timethese(-0.1, $code_to_test, 'none');
275 is(ref ($results), 'HASH', "timethese should return a hashref");
276 isa_ok($results->{Foo}, 'Benchmark', "Foo value");
277 isa_ok($results->{Bar}, 'Benchmark', "Bar value");
278 eq_set([keys %$results], [qw(Foo Bar)], 'should be exactly two objects');
279 ok ($foo > 0, "Foo code was run");
280 ok ($bar > 0, "Bar code was run");
282 ok (($end - $start) > 0.1, "benchmarked code ran for over 0.1 seconds");
285 # Remove any warnings about having too few iterations.
286 $got =~ s/\(warning:[^\)]+\)//gs;
287 is ($got =~ tr/ \t\n//c, 0, "format 'none' should suppress output");
289 my $graph_dissassembly =
290 qr!^[ \t]+(\S+)[ \t]+(\w+)[ \t]+(\w+)[ \t]* # Title line
291 \n[ \t]*(\w+)[ \t]+([0-9.]+(?:/s)?)[ \t]+(-+)[ \t]+(-?\d+%)[ \t]*
292 \n[ \t]*(\w+)[ \t]+([0-9.]+(?:/s)?)[ \t]+(-?\d+%)[ \t]+(-+)[ \t]*$!xm;
294 sub check_graph_consistency {
295 my ( $ratetext, $slowc, $fastc,
296 $slowr, $slowratet, $slowslow, $slowfastt,
297 $fastr, $fastratet, $fastslowt, $fastfast)
301 &= is ($slowc, $slowr, "left col tag should be top row tag");
303 &= is ($fastc, $fastr, "right col tag should be bottom row tag");
305 like ($slowslow, qr/^-+/, "should be dash for comparing slow with slow");
307 &= is ($slowslow, $fastfast, "slow v slow should be same as fast v fast");
308 my $slowrate = $slowratet;
309 my $fastrate = $fastratet;
310 my ($slow_is_rate, $fast_is_rate);
311 unless ($slow_is_rate = $slowrate =~ s!/s!!) {
312 # Slow is expressed as iters per second.
313 $slowrate = 1/$slowrate if $slowrate;
315 unless ($fast_is_rate = $fastrate =~ s!/s!!) {
316 # Fast is expressed as iters per second.
317 $fastrate = 1/$fastrate if $fastrate;
319 if ($ratetext =~ /rate/i) {
321 &= ok ($slow_is_rate, "slow should be expressed as a rate");
323 &= ok ($fast_is_rate, "fast should be expressed as a rate");
326 ok (!$slow_is_rate, "slow should be expressed as a iters per second");
328 ok (!$fast_is_rate, "fast should be expressed as a iters per second");
331 (my $slowfast = $slowfastt) =~ s!%!!;
332 (my $fastslow = $fastslowt) =~ s!%!!;
333 if ($slowrate < $fastrate) {
334 pass ("slow rate is less than fast rate");
335 unless (ok ($slowfast <= 0 && $slowfast >= -100,
336 "slowfast should be less than or equal to zero, and >= -100")) {
337 print STDERR "# slowfast $slowfast\n";
340 unless (ok ($fastslow > 0, "fastslow should be > 0")) {
341 print STDERR "# fastslow $fastslow\n";
346 &= is ($slowrate, $fastrate,
347 "slow rate isn't less than fast rate, so should be the same");
348 # In OpenBSD the $slowfast is sometimes a really, really, really
349 # small number less than zero, and this gets stringified as -0.
351 &= like ($slowfast, qr/^-?0$/, "slowfast should be zero");
353 &= like ($fastslow, qr/^-?0$/, "fastslow should be zero");
358 sub check_graph_vs_output {
359 my ($chart, $got) = @_;
360 my ( $ratetext, $slowc, $fastc,
361 $slowr, $slowratet, $slowslow, $slowfastt,
362 $fastr, $fastratet, $fastslowt, $fastfast)
363 = $got =~ $graph_dissassembly;
365 = check_graph_consistency ( $ratetext, $slowc, $fastc,
366 $slowr, $slowratet, $slowslow, $slowfastt,
367 $fastr, $fastratet, $fastslowt, $fastfast);
369 &= is_deeply ($chart, [['', $ratetext, $slowc, $fastc],
370 [$slowr, $slowratet, $slowslow, $slowfastt],
371 [$fastr, $fastratet, $fastslowt, $fastfast]],
372 "check the chart layout matches the formatted output");
373 unless ($all_passed) {
374 print STDERR "# Something went wrong there. I got this chart:\n";
375 print STDERR "# $_\n" foreach split /\n/, $got;
380 my ($title, $row1, $row2) = @_;
381 is (scalar @$title, 4, "Four entries in title row");
382 is (scalar @$row1, 4, "Four entries in first row");
383 is (scalar @$row2, 4, "Four entries in second row");
384 is (shift @$title, '', "First entry of output graph should be ''");
385 check_graph_consistency (@$title, @$row1, @$row2);
391 my $chart = cmpthese( -0.1, { a => "++\$i", b => "\$i = sqrt(\$i++)" }, "auto" ) ;
394 ok (($end - $start) > 0.05, "benchmarked code ran for over 0.05 seconds");
397 # Remove any warnings about having too few iterations.
398 $got =~ s/\(warning:[^\)]+\)//gs;
400 like ($got, qr/running\W+a\W+b.*?for at least 0\.1 CPU second/s,
403 $got =~ s/.*\.\.\.//s;
404 like ($got, $Default_Pattern, 'should find default format somewhere');
405 like ($got, $graph_dissassembly, "Should find the output graph somewhere");
406 check_graph_vs_output ($chart, $got);
409 # Not giving auto should suppress timethese results.
413 my $chart = cmpthese( -0.1, { a => "++\$i", b => "\$i = sqrt(\$i++)" } ) ;
416 ok (($end - $start) > 0.05, "benchmarked code ran for over 0.05 seconds");
419 # Remove any warnings about having too few iterations.
420 $got =~ s/\(warning:[^\)]+\)//gs;
422 unlike ($got, qr/running\W+a\W+b.*?for at least 0\.1 CPU second/s,
423 'should not have title');
425 $got =~ s/.*\.\.\.//s;
426 unlike ($got, $Default_Pattern, 'should not find default format somewhere');
427 like ($got, $graph_dissassembly, "Should find the output graph somewhere");
428 check_graph_vs_output ($chart, $got);
434 my $chart = cmpthese( 10, $code_to_test, 'nop' ) ;
436 ok ($foo > 0, "Foo code was run");
437 ok ($bar > 0, "Bar code was run");
440 # Remove any warnings about having too few iterations.
441 $got =~ s/\(warning:[^\)]+\)//gs;
442 like ($got, qr/timing 10 iterations of\s+Bar\W+Foo\W*?\.\.\./s,
445 $got =~ s/.*\.\.\.//s;
446 like ($got, $Nop_Pattern, 'specify format as nop');
447 like ($got, $graph_dissassembly, "Should find the output graph somewhere");
448 check_graph_vs_output ($chart, $got);
454 my $chart = cmpthese( 10, $code_to_test, 'none' ) ;
456 ok ($foo > 0, "Foo code was run");
457 ok ($bar > 0, "Bar code was run");
460 # Remove any warnings about having too few iterations.
461 $got =~ s/\(warning:[^\)]+\)//gs;
462 $got =~ s/^[ \t\n]+//s; # Remove all the whitespace from the beginning
463 is ($got, '', "format 'none' should suppress output");
464 is (ref $chart, 'ARRAY', "output should be an array ref");
465 # Some of these will go bang if the preceding test fails. There will be
466 # a big clue as to why, from the previous test's diagnostic
467 is (ref $chart->[0], 'ARRAY', "output should be an array of arrays");
468 check_graph (@$chart);
474 my $chart = cmpthese( $results ) ;
476 is ($foo, 0, "Foo code was not run");
477 is ($bar, 0, "Bar code was not run");
480 ok ($got !~ /\.\.\./s, 'check that there is no title');
481 like ($got, $graph_dissassembly, "Should find the output graph somewhere");
482 check_graph_vs_output ($chart, $got);
488 my $chart = cmpthese( $results, 'none' ) ;
490 is ($foo, 0, "Foo code was not run");
491 is ($bar, 0, "Bar code was not run");
494 is ($got, '', "'none' should suppress all output");
495 is (ref $chart, 'ARRAY', "output should be an array ref");
496 # Some of these will go bang if the preceding test fails. There will be
497 # a big clue as to why, from the previous test's diagnostic
498 is (ref $chart->[0], 'ARRAY', "output should be an array of arrays");
499 check_graph (@$chart);
502 ###}my $out = tie *OUT, 'TieOut'; my ($got); ###
504 my $debug = tie *STDERR, 'TieOut';
507 isa_ok(timeit(5, '++$bar'), 'Benchmark', "timeit eval");
508 is ($bar, 5, "benchmarked code was run 5 times");
509 is ($debug->read(), '', "There was no debug output");
515 $got = timeit(5, '++$bar');
517 isa_ok($got, 'Benchmark', "timeit eval");
518 is ($bar, 5, "benchmarked code was run 5 times");
519 is ($out->read(), '', "There was no STDOUT output with debug enabled");
520 isnt ($debug->read(), '', "There was STDERR debug output with debug enabled");
525 isa_ok(timeit(5, '++$bar'), 'Benchmark', "timeit eval");
526 is ($bar, 5, "benchmarked code was run 5 times");
527 is ($debug->read(), '', "There was no debug output debug disabled");
532 # To check the cache we are poking where we don't belong, inside the namespace.
533 # The way benchmark is written We can't actually check whehter the cache is
534 # being used, merely what's become cached.
537 my @before_keys = keys %Benchmark::Cache;
539 isa_ok(timeit(5, '++$bar'), 'Benchmark', "timeit eval");
540 is ($bar, 5, "benchmarked code was run 5 times");
541 my @after5_keys = keys %Benchmark::Cache;
543 isa_ok(timeit(10, '++$bar'), 'Benchmark', "timeit eval");
544 is ($bar, 10, "benchmarked code was run 10 times");
545 ok (!eq_array ([keys %Benchmark::Cache], \@after5_keys), "10 differs from 5");
548 # Hash key order will be the same if there are the same keys.
549 is_deeply ([keys %Benchmark::Cache], \@after5_keys,
550 "cleared 10, only cached results for 5 should remain");
553 is_deeply ([keys %Benchmark::Cache], \@before_keys,
554 "back to square 1 when we clear the cache again?");
557 { # Check usage error messages
558 my %usage = %Benchmark::_Usage;
559 delete $usage{runloop}; # not public, not worrying about it just now
561 my @takes_no_args = qw(clearallcache disablecache enablecache);
563 my %cmpthese = ('forgot {}' => 'cmpthese( 42, foo => sub { 1 } )',
564 'not result' => 'cmpthese(42)',
565 'array ref' => 'cmpthese( 42, [ foo => sub { 1 } ] )',
567 while( my($name, $code) = each %cmpthese ) {
569 is( $@, $usage{cmpthese}, "cmpthese usage: $name" );
572 my %timethese = ('forgot {}' => 'timethese( 42, foo => sub { 1 } )',
573 'no code' => 'timethese(42)',
574 'array ref' => 'timethese( 42, [ foo => sub { 1 } ] )',
577 while( my($name, $code) = each %timethese ) {
579 is( $@, $usage{timethese}, "timethese usage: $name" );
583 while( my($func, $usage) = each %usage ) {
584 next if grep $func eq $_, @takes_no_args;
586 is( $@, $usage, "$func usage: no args" );
589 foreach my $func (@takes_no_args) {
591 is( $@, $usage{$func}, "$func usage: with args" );
600 bless(\( my $ref = ''), $class);
605 $$self .= join('', @_);
610 $$self .= sprintf shift, @_;
615 return substr($$self, 0, length($$self), '');