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 cmp_ok($actual, '<=', $delta, "is $in_onesec within $delta of estimate ($estimate)")
81 or diag("# $in_onesec is between " . ($delta / 2) . " and $delta of estimate. Not that safe.");
84 # I found that the eval'ed version was 3 times faster than the coderef.
85 # (now it has a different ballast value)
87 my $again = countit(1, '$baz += fib($ballast)');
88 isa_ok($onesec, 'Benchmark', "countit 1, eval");
89 isnt ($baz, 0, "benchmarked code was run");
90 my $in_again = $again->iters;
91 print "# $in_again iterations\n";
92 ok ($in_again > 0, "iters returned positive iterations");
95 my $t1 = new Benchmark;
96 isa_ok ($t1, 'Benchmark', "Create another benchmark object now we're finished");
98 my $diff = timediff ($t1, $t0);
99 isa_ok ($diff, 'Benchmark', "Get the time difference");
100 isa_ok (timesum ($t0, $t1), 'Benchmark', "check timesum");
102 my $default = timestr ($diff);
103 isnt ($default, '', 'timestr ($diff)');
104 my $auto = timestr ($diff, 'auto');
105 is ($auto, $default, 'timestr ($diff, "auto") matches timestr ($diff)');
108 my $all = timestr ($diff, 'all');
109 like ($all, $All_Pattern, 'timestr ($diff, "all")');
112 my ($wallclock, $usr, $sys, $cusr, $csys, $cpu) = $all =~ $All_Pattern;
114 is (timestr ($diff, 'none'), '', "none supresses output");
116 my $noc = timestr ($diff, 'noc');
117 like ($noc, qr/$wallclock +wallclock secs? +\( *$usr +usr +\+ +$sys +sys += +$cpu +CPU\)/, 'timestr ($diff, "noc")');
119 my $nop = timestr ($diff, 'nop');
120 like ($nop, qr/$wallclock +wallclock secs? +\( *$cusr +cusr +\+ +$csys +csys += +\d+\.\d\d +CPU\)/, 'timestr ($diff, "nop")');
123 pass ('"auto" is "noc"');
125 is ($auto, $all, '"auto" isn\'t "noc", so should be eq to "all"');
128 like (timestr ($diff, 'all', 'E'),
129 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"]');
132 my $out = tie *OUT, 'TieOut';
138 my $got = timethis($iterations, sub {++$foo});
140 isa_ok($got, 'Benchmark', "timethis CODEREF");
141 is ($foo, $iterations, "benchmarked code was run $iterations times");
144 like ($got, qr/^timethis $iterations/, 'default title');
145 like ($got, $Default_Pattern, 'default format is all or noc');
149 $got = timethis($iterations, '++$bar');
151 isa_ok($got, 'Benchmark', "timethis eval");
152 is ($bar, $iterations, "benchmarked code was run $iterations times");
155 like ($got, qr/^timethis $iterations/, 'default title');
156 like ($got, $Default_Pattern, 'default format is all or noc');
158 my $title = 'lies, damn lies and benchmarks';
161 $got = timethis($iterations, sub {++$foo}, $title);
163 isa_ok($got, 'Benchmark', "timethis with title");
164 is ($foo, $iterations, "benchmarked code was run $iterations times");
167 like ($got, qr/^$title:/, 'specify title');
168 like ($got, $Default_Pattern, 'default format is all or noc');
170 # default is auto, which is all or noc. nop can never match the default
173 $got = timethis($iterations, sub {++$foo}, $title, 'nop');
175 isa_ok($got, 'Benchmark', "timethis with format");
176 is ($foo, $iterations, "benchmarked code was run $iterations times");
179 like ($got, qr/^$title:/, 'specify title');
180 like ($got, $Nop_Pattern, 'specify format as nop');
186 $got = timethis(-2, sub {$foo+= fib($ballast)}, $title, 'none');
189 isa_ok($got, 'Benchmark',
190 "timethis, at least 2 seconds with format 'none'");
191 ok ($foo > 0, "benchmarked code was run");
192 ok ($end - $start > 1, "benchmarked code ran for over 1 second");
195 # Remove any warnings about having too few iterations.
196 $got =~ s/\(warning:[^\)]+\)//gs;
197 $got =~ s/^[ \t\n]+//s; # Remove all the whitespace from the beginning
199 is ($got, '', "format 'none' should suppress output");
202 $foo = $bar = $baz = 0;
204 $got = timethese($iterations, { Foo => sub {++$foo}, Bar => '++$bar',
205 Baz => sub {++$baz} });
207 is(ref ($got), 'HASH', "timethese should return a hashref");
208 isa_ok($got->{Foo}, 'Benchmark', "Foo value");
209 isa_ok($got->{Bar}, 'Benchmark', "Bar value");
210 isa_ok($got->{Baz}, 'Benchmark', "Baz value");
211 eq_set([keys %$got], [qw(Foo Bar Baz)], 'should be exactly three objects');
212 is ($foo, $iterations, "Foo code was run $iterations times");
213 is ($bar, $iterations, "Bar code was run $iterations times");
214 is ($baz, $iterations, "Baz code was run $iterations times");
217 # Remove any warnings about having too few iterations.
218 $got =~ s/\(warning:[^\)]+\)//gs;
220 like ($got, qr/timing $iterations iterations of\s+Bar\W+Baz\W+Foo\W*?\.\.\./s,
223 $got =~ s/.*\.\.\.//s;
224 like ($got, qr/\bBar\b.*\bBaz\b.*\bFoo\b/s, 'check output is in sorted order');
225 like ($got, $Default_Pattern, 'should find default format somewhere');
228 { # ensure 'use strict' does not leak from Benchmark.pm into benchmarked code
234 { undeclared_var => q{ $i++; $i-- },
235 symbolic_ref => q{ $bar = 42;
243 is( $@, '', q{no strict leakage in name => 'code'} );
247 { undeclared_var => sub { $i++; $i-- },
248 symbolic_ref => sub { $bar = 42;
255 is( $@, '', q{no strict leakage in name => sub { code }} );
262 my $code_to_test = { Foo => sub {$foo+=fib($ballast-2)},
263 Bar => sub {$bar+=fib($ballast)}};
264 # Keep these for later.
270 $results = timethese(-0.1, $code_to_test, 'none');
274 is(ref ($results), 'HASH', "timethese should return a hashref");
275 isa_ok($results->{Foo}, 'Benchmark', "Foo value");
276 isa_ok($results->{Bar}, 'Benchmark', "Bar value");
277 eq_set([keys %$results], [qw(Foo Bar)], 'should be exactly two objects');
278 ok ($foo > 0, "Foo code was run");
279 ok ($bar > 0, "Bar code was run");
281 ok (($end - $start) > 0.1, "benchmarked code ran for over 0.1 seconds");
284 # Remove any warnings about having too few iterations.
285 $got =~ s/\(warning:[^\)]+\)//gs;
286 is ($got =~ tr/ \t\n//c, 0, "format 'none' should suppress output");
288 my $graph_dissassembly =
289 qr!^[ \t]+(\S+)[ \t]+(\w+)[ \t]+(\w+)[ \t]* # Title line
290 \n[ \t]*(\w+)[ \t]+([0-9.]+(?:/s)?)[ \t]+(-+)[ \t]+(-?\d+%)[ \t]*
291 \n[ \t]*(\w+)[ \t]+([0-9.]+(?:/s)?)[ \t]+(-?\d+%)[ \t]+(-+)[ \t]*$!xm;
293 sub check_graph_consistency {
294 my ( $ratetext, $slowc, $fastc,
295 $slowr, $slowratet, $slowslow, $slowfastt,
296 $fastr, $fastratet, $fastslowt, $fastfast)
300 &= is ($slowc, $slowr, "left col tag should be top row tag");
302 &= is ($fastc, $fastr, "right col tag should be bottom row tag");
304 like ($slowslow, qr/^-+/, "should be dash for comparing slow with slow");
306 &= is ($slowslow, $fastfast, "slow v slow should be same as fast v fast");
307 my $slowrate = $slowratet;
308 my $fastrate = $fastratet;
309 my ($slow_is_rate, $fast_is_rate);
310 unless ($slow_is_rate = $slowrate =~ s!/s!!) {
311 # Slow is expressed as iters per second.
312 $slowrate = 1/$slowrate if $slowrate;
314 unless ($fast_is_rate = $fastrate =~ s!/s!!) {
315 # Fast is expressed as iters per second.
316 $fastrate = 1/$fastrate if $fastrate;
318 if ($ratetext =~ /rate/i) {
320 &= ok ($slow_is_rate, "slow should be expressed as a rate");
322 &= ok ($fast_is_rate, "fast should be expressed as a rate");
325 ok (!$slow_is_rate, "slow should be expressed as a iters per second");
327 ok (!$fast_is_rate, "fast should be expressed as a iters per second");
330 (my $slowfast = $slowfastt) =~ s!%!!;
331 (my $fastslow = $fastslowt) =~ s!%!!;
332 if ($slowrate < $fastrate) {
333 pass ("slow rate is less than fast rate");
334 unless (ok ($slowfast <= 0 && $slowfast >= -100,
335 "slowfast should be less than or equal to zero, and >= -100")) {
336 print STDERR "# slowfast $slowfast\n";
339 unless (ok ($fastslow > 0, "fastslow should be > 0")) {
340 print STDERR "# fastslow $fastslow\n";
345 &= is ($slowrate, $fastrate,
346 "slow rate isn't less than fast rate, so should be the same");
347 # In OpenBSD the $slowfast is sometimes a really, really, really
348 # small number less than zero, and this gets stringified as -0.
350 &= like ($slowfast, qr/^-?0$/, "slowfast should be zero");
352 &= like ($fastslow, qr/^-?0$/, "fastslow should be zero");
357 sub check_graph_vs_output {
358 my ($chart, $got) = @_;
359 my ( $ratetext, $slowc, $fastc,
360 $slowr, $slowratet, $slowslow, $slowfastt,
361 $fastr, $fastratet, $fastslowt, $fastfast)
362 = $got =~ $graph_dissassembly;
364 = check_graph_consistency ( $ratetext, $slowc, $fastc,
365 $slowr, $slowratet, $slowslow, $slowfastt,
366 $fastr, $fastratet, $fastslowt, $fastfast);
368 &= is_deeply ($chart, [['', $ratetext, $slowc, $fastc],
369 [$slowr, $slowratet, $slowslow, $slowfastt],
370 [$fastr, $fastratet, $fastslowt, $fastfast]],
371 "check the chart layout matches the formatted output");
372 unless ($all_passed) {
373 print STDERR "# Something went wrong there. I got this chart:\n";
374 print STDERR "# $_\n" foreach split /\n/, $got;
379 my ($title, $row1, $row2) = @_;
380 is (scalar @$title, 4, "Four entries in title row");
381 is (scalar @$row1, 4, "Four entries in first row");
382 is (scalar @$row2, 4, "Four entries in second row");
383 is (shift @$title, '', "First entry of output graph should be ''");
384 check_graph_consistency (@$title, @$row1, @$row2);
390 my $chart = cmpthese( -0.1, { a => "++\$i", b => "\$i = sqrt(\$i++)" }, "auto" ) ;
393 ok (($end - $start) > 0.05, "benchmarked code ran for over 0.05 seconds");
396 # Remove any warnings about having too few iterations.
397 $got =~ s/\(warning:[^\)]+\)//gs;
399 like ($got, qr/running\W+a\W+b.*?for at least 0\.1 CPU second/s,
402 $got =~ s/.*\.\.\.//s;
403 like ($got, $Default_Pattern, 'should find default format somewhere');
404 like ($got, $graph_dissassembly, "Should find the output graph somewhere");
405 check_graph_vs_output ($chart, $got);
408 # Not giving auto should suppress timethese results.
412 my $chart = cmpthese( -0.1, { a => "++\$i", b => "\$i = sqrt(\$i++)" } ) ;
415 ok (($end - $start) > 0.05, "benchmarked code ran for over 0.05 seconds");
418 # Remove any warnings about having too few iterations.
419 $got =~ s/\(warning:[^\)]+\)//gs;
421 unlike ($got, qr/running\W+a\W+b.*?for at least 0\.1 CPU second/s,
422 'should not have title');
424 $got =~ s/.*\.\.\.//s;
425 unlike ($got, $Default_Pattern, 'should not find default format somewhere');
426 like ($got, $graph_dissassembly, "Should find the output graph somewhere");
427 check_graph_vs_output ($chart, $got);
433 my $chart = cmpthese( 10, $code_to_test, 'nop' ) ;
435 ok ($foo > 0, "Foo code was run");
436 ok ($bar > 0, "Bar code was run");
439 # Remove any warnings about having too few iterations.
440 $got =~ s/\(warning:[^\)]+\)//gs;
441 like ($got, qr/timing 10 iterations of\s+Bar\W+Foo\W*?\.\.\./s,
444 $got =~ s/.*\.\.\.//s;
445 like ($got, $Nop_Pattern, 'specify format as nop');
446 like ($got, $graph_dissassembly, "Should find the output graph somewhere");
447 check_graph_vs_output ($chart, $got);
453 my $chart = cmpthese( 10, $code_to_test, 'none' ) ;
455 ok ($foo > 0, "Foo code was run");
456 ok ($bar > 0, "Bar code was run");
459 # Remove any warnings about having too few iterations.
460 $got =~ s/\(warning:[^\)]+\)//gs;
461 $got =~ s/^[ \t\n]+//s; # Remove all the whitespace from the beginning
462 is ($got, '', "format 'none' should suppress output");
463 is (ref $chart, 'ARRAY', "output should be an array ref");
464 # Some of these will go bang if the preceding test fails. There will be
465 # a big clue as to why, from the previous test's diagnostic
466 is (ref $chart->[0], 'ARRAY', "output should be an array of arrays");
467 check_graph (@$chart);
473 my $chart = cmpthese( $results ) ;
475 is ($foo, 0, "Foo code was not run");
476 is ($bar, 0, "Bar code was not run");
479 ok ($got !~ /\.\.\./s, 'check that there is no title');
480 like ($got, $graph_dissassembly, "Should find the output graph somewhere");
481 check_graph_vs_output ($chart, $got);
487 my $chart = cmpthese( $results, 'none' ) ;
489 is ($foo, 0, "Foo code was not run");
490 is ($bar, 0, "Bar code was not run");
493 is ($got, '', "'none' should suppress all output");
494 is (ref $chart, 'ARRAY', "output should be an array ref");
495 # Some of these will go bang if the preceding test fails. There will be
496 # a big clue as to why, from the previous test's diagnostic
497 is (ref $chart->[0], 'ARRAY', "output should be an array of arrays");
498 check_graph (@$chart);
501 ###}my $out = tie *OUT, 'TieOut'; my ($got); ###
503 my $debug = tie *STDERR, 'TieOut';
506 isa_ok(timeit(5, '++$bar'), 'Benchmark', "timeit eval");
507 is ($bar, 5, "benchmarked code was run 5 times");
508 is ($debug->read(), '', "There was no debug output");
514 $got = timeit(5, '++$bar');
516 isa_ok($got, 'Benchmark', "timeit eval");
517 is ($bar, 5, "benchmarked code was run 5 times");
518 is ($out->read(), '', "There was no STDOUT output with debug enabled");
519 isnt ($debug->read(), '', "There was STDERR debug output with debug enabled");
524 isa_ok(timeit(5, '++$bar'), 'Benchmark', "timeit eval");
525 is ($bar, 5, "benchmarked code was run 5 times");
526 is ($debug->read(), '', "There was no debug output debug disabled");
531 # To check the cache we are poking where we don't belong, inside the namespace.
532 # The way benchmark is written We can't actually check whehter the cache is
533 # being used, merely what's become cached.
536 my @before_keys = keys %Benchmark::Cache;
538 isa_ok(timeit(5, '++$bar'), 'Benchmark', "timeit eval");
539 is ($bar, 5, "benchmarked code was run 5 times");
540 my @after5_keys = keys %Benchmark::Cache;
542 isa_ok(timeit(10, '++$bar'), 'Benchmark', "timeit eval");
543 is ($bar, 10, "benchmarked code was run 10 times");
544 ok (!eq_array ([keys %Benchmark::Cache], \@after5_keys), "10 differs from 5");
547 # Hash key order will be the same if there are the same keys.
548 is_deeply ([keys %Benchmark::Cache], \@after5_keys,
549 "cleared 10, only cached results for 5 should remain");
552 is_deeply ([keys %Benchmark::Cache], \@before_keys,
553 "back to square 1 when we clear the cache again?");
556 { # Check usage error messages
557 my %usage = %Benchmark::_Usage;
558 delete $usage{runloop}; # not public, not worrying about it just now
560 my @takes_no_args = qw(clearallcache disablecache enablecache);
562 my %cmpthese = ('forgot {}' => 'cmpthese( 42, foo => sub { 1 } )',
563 'not result' => 'cmpthese(42)',
564 'array ref' => 'cmpthese( 42, [ foo => sub { 1 } ] )',
566 while( my($name, $code) = each %cmpthese ) {
568 is( $@, $usage{cmpthese}, "cmpthese usage: $name" );
571 my %timethese = ('forgot {}' => 'timethese( 42, foo => sub { 1 } )',
572 'no code' => 'timethese(42)',
573 'array ref' => 'timethese( 42, [ foo => sub { 1 } ] )',
576 while( my($name, $code) = each %timethese ) {
578 is( $@, $usage{timethese}, "timethese usage: $name" );
582 while( my($func, $usage) = each %usage ) {
583 next if grep $func eq $_, @takes_no_args;
585 is( $@, $usage, "$func usage: no args" );
588 foreach my $func (@takes_no_args) {
590 is( $@, $usage{$func}, "$func usage: with args" );
599 bless(\( my $ref = ''), $class);
604 $$self .= join('', @_);
609 $$self .= sprintf shift, @_;
614 return substr($$self, 0, length($$self), '');