10 use vars qw($foo $bar $baz $ballast);
11 use Test::More tests => 196;
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 parentheses 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=$in_threesecs iterations\n";
65 ok ($in_threesecs > 0, "iters returned positive iterations");
66 my $cpu3 = $threesecs->[1]; # user
67 my $sys3 = $threesecs->[2]; # sys
68 cmp_ok($cpu3+$sys3, '>=', 3.0, "3s cpu3 is at least 3s");
69 my $in_threesecs_adj = $in_threesecs;
70 $in_threesecs_adj *= (3/$cpu3); # adjust because may not have run for exactly 3s
71 print "# in_threesecs_adj=$in_threesecs_adj adjusted iterations\n";
73 my $estimate = int (100 * $in_threesecs_adj / 3) / 100;
74 print "# from the 3 second run estimate $estimate iterations in 1 second...\n";
76 my $onesec = countit(1, $coderef);
77 isa_ok($onesec, 'Benchmark', "countit 1, CODEREF");
78 isnt ($baz, 0, "benchmarked code was run");
79 my $in_onesec = $onesec->iters;
80 print "# in_onesec=$in_onesec iterations\n";
81 ok ($in_onesec > 0, "iters returned positive iterations");
82 my $cpu1 = $onesec->[1]; # user
83 my $sys1 = $onesec->[2]; # sys
84 cmp_ok($cpu1+$sys1, '>=', 1.0, "is cpu1 is at least 1s");
85 my $in_onesec_adj = $in_onesec;
86 $in_onesec_adj *= (1/$cpu1); # adjust because may not have run for exactly 1s
87 print "# in_onesec_adj=$in_onesec_adj adjusted iterations\n";
90 my $difference = $in_onesec_adj - $estimate;
91 my $actual = abs ($difference / $in_onesec_adj);
92 cmp_ok($actual, '<=', $delta, "is $in_onesec_adj within $delta of estimate ($estimate)")
94 diag(" in_threesecs = $in_threesecs");
95 diag(" in_threesecs_adj = $in_threesecs_adj");
96 diag(" cpu3 = $cpu3");
97 diag(" sys3 = $sys3");
98 diag(" estimate = $estimate");
99 diag(" in_onesec = $in_onesec");
100 diag(" in_onesec_adj = $in_onesec_adj");
101 diag(" cpu1 = $cpu1");
102 diag(" sys1 = $sys1");
106 # I found that the eval'ed version was 3 times faster than the coderef.
107 # (now it has a different ballast value)
109 my $again = countit(1, '$baz += fib($ballast)');
110 isa_ok($onesec, 'Benchmark', "countit 1, eval");
111 isnt ($baz, 0, "benchmarked code was run");
112 my $in_again = $again->iters;
113 print "# $in_again iterations\n";
114 ok ($in_again > 0, "iters returned positive iterations");
117 my $t1 = new Benchmark;
118 isa_ok ($t1, 'Benchmark', "Create another benchmark object now we're finished");
120 my $diff = timediff ($t1, $t0);
121 isa_ok ($diff, 'Benchmark', "Get the time difference");
122 isa_ok (timesum ($t0, $t1), 'Benchmark', "check timesum");
124 my $default = timestr ($diff);
125 isnt ($default, '', 'timestr ($diff)');
126 my $auto = timestr ($diff, 'auto');
127 is ($auto, $default, 'timestr ($diff, "auto") matches timestr ($diff)');
130 my $all = timestr ($diff, 'all');
131 like ($all, $All_Pattern, 'timestr ($diff, "all")');
134 my ($wallclock, $usr, $sys, $cusr, $csys, $cpu) = $all =~ $All_Pattern;
136 is (timestr ($diff, 'none'), '', "none suppresses output");
138 my $noc = timestr ($diff, 'noc');
139 like ($noc, qr/$wallclock +wallclock secs? +\( *$usr +usr +\+ +$sys +sys += +\d+\.\d\d +CPU\)/, 'timestr ($diff, "noc")');
141 my $nop = timestr ($diff, 'nop');
142 like ($nop, qr/$wallclock +wallclock secs? +\( *$cusr +cusr +\+ +$csys +csys += +\d+\.\d\d +CPU\)/, 'timestr ($diff, "nop")');
145 pass ('"auto" is "noc"');
147 is ($auto, $all, '"auto" isn\'t "noc", so should be eq to "all"');
150 like (timestr ($diff, 'all', 'E'),
151 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"]');
154 my $out = tie *OUT, 'TieOut';
160 my $got = timethis($iterations, sub {++$foo});
162 isa_ok($got, 'Benchmark', "timethis CODEREF");
163 is ($foo, $iterations, "benchmarked code was run $iterations times");
166 like ($got, qr/^timethis $iterations/, 'default title');
167 like ($got, $Default_Pattern, 'default format is all or noc');
171 $got = timethis($iterations, '++$bar');
173 isa_ok($got, 'Benchmark', "timethis eval");
174 is ($bar, $iterations, "benchmarked code was run $iterations times");
177 like ($got, qr/^timethis $iterations/, 'default title');
178 like ($got, $Default_Pattern, 'default format is all or noc');
180 my $title = 'lies, damn lies and benchmarks';
183 $got = timethis($iterations, sub {++$foo}, $title);
185 isa_ok($got, 'Benchmark', "timethis with title");
186 is ($foo, $iterations, "benchmarked code was run $iterations times");
189 like ($got, qr/^$title:/, 'specify title');
190 like ($got, $Default_Pattern, 'default format is all or noc');
192 # default is auto, which is all or noc. nop can never match the default
195 $got = timethis($iterations, sub {++$foo}, $title, 'nop');
197 isa_ok($got, 'Benchmark', "timethis with format");
198 is ($foo, $iterations, "benchmarked code was run $iterations times");
201 like ($got, qr/^$title:/, 'specify title');
202 like ($got, $Nop_Pattern, 'specify format as nop');
208 $got = timethis(-2, sub {$foo+= fib($ballast)}, $title, 'none');
211 isa_ok($got, 'Benchmark',
212 "timethis, at least 2 seconds with format 'none'");
213 ok ($foo > 0, "benchmarked code was run");
214 ok ($end - $start > 1, "benchmarked code ran for over 1 second");
217 # Remove any warnings about having too few iterations.
218 $got =~ s/\(warning:[^\)]+\)//gs;
219 $got =~ s/^[ \t\n]+//s; # Remove all the whitespace from the beginning
221 is ($got, '', "format 'none' should suppress output");
224 $foo = $bar = $baz = 0;
226 $got = timethese($iterations, { Foo => sub {++$foo}, Bar => '++$bar',
227 Baz => sub {++$baz} });
229 is(ref ($got), 'HASH', "timethese should return a hashref");
230 isa_ok($got->{Foo}, 'Benchmark', "Foo value");
231 isa_ok($got->{Bar}, 'Benchmark', "Bar value");
232 isa_ok($got->{Baz}, 'Benchmark', "Baz value");
233 eq_set([keys %$got], [qw(Foo Bar Baz)], 'should be exactly three objects');
234 is ($foo, $iterations, "Foo code was run $iterations times");
235 is ($bar, $iterations, "Bar code was run $iterations times");
236 is ($baz, $iterations, "Baz code was run $iterations times");
239 # Remove any warnings about having too few iterations.
240 $got =~ s/\(warning:[^\)]+\)//gs;
242 like ($got, qr/timing $iterations iterations of\s+Bar\W+Baz\W+Foo\W*?\.\.\./s,
245 $got =~ s/.*\.\.\.//s;
246 like ($got, qr/\bBar\b.*\bBaz\b.*\bFoo\b/s, 'check output is in sorted order');
247 like ($got, $Default_Pattern, 'should find default format somewhere');
250 { # ensure 'use strict' does not leak from Benchmark.pm into benchmarked code
256 { undeclared_var => q{ $i++; $i-- },
257 symbolic_ref => q{ $bar = 42;
265 is( $@, '', q{no strict leakage in name => 'code'} );
269 { undeclared_var => sub { $i++; $i-- },
270 symbolic_ref => sub { $bar = 42;
277 is( $@, '', q{no strict leakage in name => sub { code }} );
284 my $code_to_test = { Foo => sub {$foo+=fib($ballast-2)},
285 Bar => sub {$bar+=fib($ballast)}};
286 # Keep these for later.
292 $results = timethese(-0.1, $code_to_test, 'none');
296 is(ref ($results), 'HASH', "timethese should return a hashref");
297 isa_ok($results->{Foo}, 'Benchmark', "Foo value");
298 isa_ok($results->{Bar}, 'Benchmark', "Bar value");
299 eq_set([keys %$results], [qw(Foo Bar)], 'should be exactly two objects');
300 ok ($foo > 0, "Foo code was run");
301 ok ($bar > 0, "Bar code was run");
303 ok (($end - $start) > 0.1, "benchmarked code ran for over 0.1 seconds");
306 # Remove any warnings about having too few iterations.
307 $got =~ s/\(warning:[^\)]+\)//gs;
308 is ($got =~ tr/ \t\n//c, 0, "format 'none' should suppress output");
310 my $graph_dissassembly =
311 qr!^[ \t]+(\S+)[ \t]+(\w+)[ \t]+(\w+)[ \t]* # Title line
312 \n[ \t]*(\w+)[ \t]+([0-9.]+(?:/s)?)[ \t]+(-+)[ \t]+(-?\d+%)[ \t]*
313 \n[ \t]*(\w+)[ \t]+([0-9.]+(?:/s)?)[ \t]+(-?\d+%)[ \t]+(-+)[ \t]*$!xm;
315 sub check_graph_consistency {
316 my ( $ratetext, $slowc, $fastc,
317 $slowr, $slowratet, $slowslow, $slowfastt,
318 $fastr, $fastratet, $fastslowt, $fastfast)
320 note("calling check_graph_consistency from line " . (caller(1))[2]);
323 &= is ($slowc, $slowr, "left col tag should be top row tag");
325 &= is ($fastc, $fastr, "right col tag should be bottom row tag");
327 like ($slowslow, qr/^-+/, "should be dash for comparing slow with slow");
329 &= is ($slowslow, $fastfast, "slow v slow should be same as fast v fast");
330 my $slowrate = $slowratet;
331 my $fastrate = $fastratet;
332 my ($slow_is_rate, $fast_is_rate);
333 unless ($slow_is_rate = $slowrate =~ s!/s!!) {
334 # Slow is expressed as iters per second.
335 $slowrate = 1/$slowrate if $slowrate;
337 unless ($fast_is_rate = $fastrate =~ s!/s!!) {
338 # Fast is expressed as iters per second.
339 $fastrate = 1/$fastrate if $fastrate;
341 if ($ratetext =~ /rate/i) {
343 &= ok ($slow_is_rate, "slow should be expressed as a rate");
345 &= ok ($fast_is_rate, "fast should be expressed as a rate");
348 ok (!$slow_is_rate, "slow should be expressed as a iters per second");
350 ok (!$fast_is_rate, "fast should be expressed as a iters per second");
353 (my $slowfast = $slowfastt) =~ s!%!!;
354 (my $fastslow = $fastslowt) =~ s!%!!;
355 if ($slowrate < $fastrate) {
356 pass ("slow rate is less than fast rate");
357 unless (ok ($slowfast <= 0 && $slowfast >= -100,
358 "slowfast should be less than or equal to zero, and >= -100")) {
359 print STDERR "# slowfast $slowfast\n";
362 unless (ok ($fastslow > 0, "fastslow should be > 0")) {
363 print STDERR "# fastslow $fastslow\n";
368 &= is ($slowrate, $fastrate,
369 "slow rate isn't less than fast rate, so should be the same");
370 # In OpenBSD the $slowfast is sometimes a really, really, really
371 # small number less than zero, and this gets stringified as -0.
373 &= like ($slowfast, qr/^-?0$/, "slowfast should be zero");
375 &= like ($fastslow, qr/^-?0$/, "fastslow should be zero");
380 sub check_graph_vs_output {
381 my ($chart, $got) = @_;
382 my ( $ratetext, $slowc, $fastc,
383 $slowr, $slowratet, $slowslow, $slowfastt,
384 $fastr, $fastratet, $fastslowt, $fastfast)
385 = $got =~ $graph_dissassembly;
387 = check_graph_consistency ( $ratetext, $slowc, $fastc,
388 $slowr, $slowratet, $slowslow, $slowfastt,
389 $fastr, $fastratet, $fastslowt, $fastfast);
391 &= is_deeply ($chart, [['', $ratetext, $slowc, $fastc],
392 [$slowr, $slowratet, $slowslow, $slowfastt],
393 [$fastr, $fastratet, $fastslowt, $fastfast]],
394 "check the chart layout matches the formatted output");
395 unless ($all_passed) {
396 print STDERR "# Something went wrong there. I got this chart:\n";
397 print STDERR "# $_\n" foreach split /\n/, $got;
402 my ($title, $row1, $row2) = @_;
403 is (scalar @$title, 4, "Four entries in title row");
404 is (scalar @$row1, 4, "Four entries in first row");
405 is (scalar @$row2, 4, "Four entries in second row");
406 is (shift @$title, '', "First entry of output graph should be ''");
407 check_graph_consistency (@$title, @$row1, @$row2);
413 my $chart = cmpthese( -0.1, { a => "++\$i", b => "\$i = sqrt(\$i++)" }, "auto" ) ;
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 like ($got, qr/running\W+a\W+b.*?for at least 0\.1 CPU second/s,
425 $got =~ s/.*\.\.\.//s;
426 like ($got, $Default_Pattern, 'should find default format somewhere');
427 like ($got, $graph_dissassembly, "Should find the output graph somewhere");
428 check_graph_vs_output ($chart, $got);
431 # Not giving auto should suppress timethese results.
435 my $chart = cmpthese( -0.1, { a => "++\$i", b => "\$i = sqrt(\$i++)" } ) ;
438 ok (($end - $start) > 0.05, "benchmarked code ran for over 0.05 seconds");
441 # Remove any warnings about having too few iterations.
442 $got =~ s/\(warning:[^\)]+\)//gs;
444 unlike ($got, qr/running\W+a\W+b.*?for at least 0\.1 CPU second/s,
445 'should not have title');
447 $got =~ s/.*\.\.\.//s;
448 unlike ($got, $Default_Pattern, 'should not find default format somewhere');
449 like ($got, $graph_dissassembly, "Should find the output graph somewhere");
450 check_graph_vs_output ($chart, $got);
456 my $chart = cmpthese( 10, $code_to_test, 'nop' ) ;
458 ok ($foo > 0, "Foo code was run");
459 ok ($bar > 0, "Bar code was run");
462 # Remove any warnings about having too few iterations.
463 $got =~ s/\(warning:[^\)]+\)//gs;
464 like ($got, qr/timing 10 iterations of\s+Bar\W+Foo\W*?\.\.\./s,
467 $got =~ s/.*\.\.\.//s;
468 like ($got, $Nop_Pattern, 'specify format as nop');
469 like ($got, $graph_dissassembly, "Should find the output graph somewhere");
470 check_graph_vs_output ($chart, $got);
476 my $chart = cmpthese( 10, $code_to_test, 'none' ) ;
478 ok ($foo > 0, "Foo code was run");
479 ok ($bar > 0, "Bar code was run");
482 # Remove any warnings about having too few iterations.
483 $got =~ s/\(warning:[^\)]+\)//gs;
484 $got =~ s/^[ \t\n]+//s; # Remove all the whitespace from the beginning
485 is ($got, '', "format 'none' should suppress output");
486 is (ref $chart, 'ARRAY', "output should be an array ref");
487 # Some of these will go bang if the preceding test fails. There will be
488 # a big clue as to why, from the previous test's diagnostic
489 is (ref $chart->[0], 'ARRAY', "output should be an array of arrays");
490 check_graph (@$chart);
496 my $chart = cmpthese( $results ) ;
498 is ($foo, 0, "Foo code was not run");
499 is ($bar, 0, "Bar code was not run");
502 ok ($got !~ /\.\.\./s, 'check that there is no title');
503 like ($got, $graph_dissassembly, "Should find the output graph somewhere");
504 check_graph_vs_output ($chart, $got);
510 my $chart = cmpthese( $results, 'none' ) ;
512 is ($foo, 0, "Foo code was not run");
513 is ($bar, 0, "Bar code was not run");
516 is ($got, '', "'none' should suppress all output");
517 is (ref $chart, 'ARRAY', "output should be an array ref");
518 # Some of these will go bang if the preceding test fails. There will be
519 # a big clue as to why, from the previous test's diagnostic
520 is (ref $chart->[0], 'ARRAY', "output should be an array of arrays");
521 check_graph (@$chart);
524 ###}my $out = tie *OUT, 'TieOut'; my ($got); ###
526 my $debug = tie *STDERR, 'TieOut';
529 isa_ok(timeit(5, '++$bar'), 'Benchmark', "timeit eval");
530 is ($bar, 5, "benchmarked code was run 5 times");
531 is ($debug->read(), '', "There was no debug output");
537 $got = timeit(5, '++$bar');
539 isa_ok($got, 'Benchmark', "timeit eval");
540 is ($bar, 5, "benchmarked code was run 5 times");
541 is ($out->read(), '', "There was no STDOUT output with debug enabled");
542 isnt ($debug->read(), '', "There was STDERR debug output with debug enabled");
547 isa_ok(timeit(5, '++$bar'), 'Benchmark', "timeit eval");
548 is ($bar, 5, "benchmarked code was run 5 times");
549 is ($debug->read(), '', "There was no debug output debug disabled");
554 # To check the cache we are poking where we don't belong, inside the namespace.
555 # The way benchmark is written we can't actually check whether the cache is
556 # being used, merely what's become cached.
559 my @before_keys = keys %Benchmark::Cache;
561 isa_ok(timeit(5, '++$bar'), 'Benchmark', "timeit eval");
562 is ($bar, 5, "benchmarked code was run 5 times");
563 my @after5_keys = keys %Benchmark::Cache;
565 isa_ok(timeit(10, '++$bar'), 'Benchmark', "timeit eval");
566 is ($bar, 10, "benchmarked code was run 10 times");
567 ok (!eq_array ([keys %Benchmark::Cache], \@after5_keys), "10 differs from 5");
570 # Hash key order will be the same if there are the same keys.
571 is_deeply ([keys %Benchmark::Cache], \@after5_keys,
572 "cleared 10, only cached results for 5 should remain");
575 is_deeply ([keys %Benchmark::Cache], \@before_keys,
576 "back to square 1 when we clear the cache again?");
579 { # Check usage error messages
580 my %usage = %Benchmark::_Usage;
581 delete $usage{runloop}; # not public, not worrying about it just now
583 my @takes_no_args = qw(clearallcache disablecache enablecache);
585 my %cmpthese = ('forgot {}' => 'cmpthese( 42, foo => sub { 1 } )',
586 'not result' => 'cmpthese(42)',
587 'array ref' => 'cmpthese( 42, [ foo => sub { 1 } ] )',
589 while( my($name, $code) = each %cmpthese ) {
591 is( $@, $usage{cmpthese}, "cmpthese usage: $name" );
594 my %timethese = ('forgot {}' => 'timethese( 42, foo => sub { 1 } )',
595 'no code' => 'timethese(42)',
596 'array ref' => 'timethese( 42, [ foo => sub { 1 } ] )',
599 while( my($name, $code) = each %timethese ) {
601 is( $@, $usage{timethese}, "timethese usage: $name" );
605 while( my($func, $usage) = each %usage ) {
606 next if grep $func eq $_, @takes_no_args;
608 is( $@, $usage, "$func usage: no args" );
611 foreach my $func (@takes_no_args) {
613 is( $@, $usage{$func}, "$func usage: with args" );
622 bless(\( my $ref = ''), $class);
627 $$self .= join('', @_);
632 $$self .= sprintf shift, @_;
637 return substr($$self, 0, length($$self), '');