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 $cpu = $threesecs->[1] + $threesecs->[2]; # user + sys
67 cmp_ok($cpu, '>=', 3.0, "3s cpu is at least 3s");
68 $in_threesecs *= (3/$cpu); # adjust because may not have run for exactly 3s
69 print "# in_threesecs=$in_threesecs adjusted iterations\n";
71 my $estimate = int (100 * $in_threesecs / 3) / 100;
72 print "# from the 3 second run estimate $estimate iterations in 1 second...\n";
74 my $onesec = countit(1, $coderef);
75 isa_ok($onesec, 'Benchmark', "countit 1, CODEREF");
76 isnt ($baz, 0, "benchmarked code was run");
77 my $in_onesec = $onesec->iters;
78 print "# in_onesec=$in_onesec iterations\n";
79 ok ($in_onesec > 0, "iters returned positive iterations");
80 $cpu = $onesec->[1] + $onesec->[2]; # user + sys
81 cmp_ok($cpu, '>=', 1.0, "1s cpu is at least 1s");
82 $in_onesec *= (1/$cpu); # adjust because may not have run for exactly 1s
83 print "# in_onesec=$in_onesec adjusted iterations\n";
86 my $difference = $in_onesec - $estimate;
87 my $actual = abs ($difference / $in_onesec);
88 cmp_ok($actual, '<=', $delta, "is $in_onesec within $delta of estimate ($estimate)")
89 or diag("# $in_onesec is between " . ($delta / 2) . " and $delta of estimate. Not that safe.");
92 # I found that the eval'ed version was 3 times faster than the coderef.
93 # (now it has a different ballast value)
95 my $again = countit(1, '$baz += fib($ballast)');
96 isa_ok($onesec, 'Benchmark', "countit 1, eval");
97 isnt ($baz, 0, "benchmarked code was run");
98 my $in_again = $again->iters;
99 print "# $in_again iterations\n";
100 ok ($in_again > 0, "iters returned positive iterations");
103 my $t1 = new Benchmark;
104 isa_ok ($t1, 'Benchmark', "Create another benchmark object now we're finished");
106 my $diff = timediff ($t1, $t0);
107 isa_ok ($diff, 'Benchmark', "Get the time difference");
108 isa_ok (timesum ($t0, $t1), 'Benchmark', "check timesum");
110 my $default = timestr ($diff);
111 isnt ($default, '', 'timestr ($diff)');
112 my $auto = timestr ($diff, 'auto');
113 is ($auto, $default, 'timestr ($diff, "auto") matches timestr ($diff)');
116 my $all = timestr ($diff, 'all');
117 like ($all, $All_Pattern, 'timestr ($diff, "all")');
120 my ($wallclock, $usr, $sys, $cusr, $csys, $cpu) = $all =~ $All_Pattern;
122 is (timestr ($diff, 'none'), '', "none suppresses output");
124 my $noc = timestr ($diff, 'noc');
125 like ($noc, qr/$wallclock +wallclock secs? +\( *$usr +usr +\+ +$sys +sys += +$cpu +CPU\)/, 'timestr ($diff, "noc")');
127 my $nop = timestr ($diff, 'nop');
128 like ($nop, qr/$wallclock +wallclock secs? +\( *$cusr +cusr +\+ +$csys +csys += +\d+\.\d\d +CPU\)/, 'timestr ($diff, "nop")');
131 pass ('"auto" is "noc"');
133 is ($auto, $all, '"auto" isn\'t "noc", so should be eq to "all"');
136 like (timestr ($diff, 'all', 'E'),
137 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"]');
140 my $out = tie *OUT, 'TieOut';
146 my $got = timethis($iterations, sub {++$foo});
148 isa_ok($got, 'Benchmark', "timethis CODEREF");
149 is ($foo, $iterations, "benchmarked code was run $iterations times");
152 like ($got, qr/^timethis $iterations/, 'default title');
153 like ($got, $Default_Pattern, 'default format is all or noc');
157 $got = timethis($iterations, '++$bar');
159 isa_ok($got, 'Benchmark', "timethis eval");
160 is ($bar, $iterations, "benchmarked code was run $iterations times");
163 like ($got, qr/^timethis $iterations/, 'default title');
164 like ($got, $Default_Pattern, 'default format is all or noc');
166 my $title = 'lies, damn lies and benchmarks';
169 $got = timethis($iterations, sub {++$foo}, $title);
171 isa_ok($got, 'Benchmark', "timethis with title");
172 is ($foo, $iterations, "benchmarked code was run $iterations times");
175 like ($got, qr/^$title:/, 'specify title');
176 like ($got, $Default_Pattern, 'default format is all or noc');
178 # default is auto, which is all or noc. nop can never match the default
181 $got = timethis($iterations, sub {++$foo}, $title, 'nop');
183 isa_ok($got, 'Benchmark', "timethis with format");
184 is ($foo, $iterations, "benchmarked code was run $iterations times");
187 like ($got, qr/^$title:/, 'specify title');
188 like ($got, $Nop_Pattern, 'specify format as nop');
194 $got = timethis(-2, sub {$foo+= fib($ballast)}, $title, 'none');
197 isa_ok($got, 'Benchmark',
198 "timethis, at least 2 seconds with format 'none'");
199 ok ($foo > 0, "benchmarked code was run");
200 ok ($end - $start > 1, "benchmarked code ran for over 1 second");
203 # Remove any warnings about having too few iterations.
204 $got =~ s/\(warning:[^\)]+\)//gs;
205 $got =~ s/^[ \t\n]+//s; # Remove all the whitespace from the beginning
207 is ($got, '', "format 'none' should suppress output");
210 $foo = $bar = $baz = 0;
212 $got = timethese($iterations, { Foo => sub {++$foo}, Bar => '++$bar',
213 Baz => sub {++$baz} });
215 is(ref ($got), 'HASH', "timethese should return a hashref");
216 isa_ok($got->{Foo}, 'Benchmark', "Foo value");
217 isa_ok($got->{Bar}, 'Benchmark', "Bar value");
218 isa_ok($got->{Baz}, 'Benchmark', "Baz value");
219 eq_set([keys %$got], [qw(Foo Bar Baz)], 'should be exactly three objects');
220 is ($foo, $iterations, "Foo code was run $iterations times");
221 is ($bar, $iterations, "Bar code was run $iterations times");
222 is ($baz, $iterations, "Baz code was run $iterations times");
225 # Remove any warnings about having too few iterations.
226 $got =~ s/\(warning:[^\)]+\)//gs;
228 like ($got, qr/timing $iterations iterations of\s+Bar\W+Baz\W+Foo\W*?\.\.\./s,
231 $got =~ s/.*\.\.\.//s;
232 like ($got, qr/\bBar\b.*\bBaz\b.*\bFoo\b/s, 'check output is in sorted order');
233 like ($got, $Default_Pattern, 'should find default format somewhere');
236 { # ensure 'use strict' does not leak from Benchmark.pm into benchmarked code
242 { undeclared_var => q{ $i++; $i-- },
243 symbolic_ref => q{ $bar = 42;
251 is( $@, '', q{no strict leakage in name => 'code'} );
255 { undeclared_var => sub { $i++; $i-- },
256 symbolic_ref => sub { $bar = 42;
263 is( $@, '', q{no strict leakage in name => sub { code }} );
270 my $code_to_test = { Foo => sub {$foo+=fib($ballast-2)},
271 Bar => sub {$bar+=fib($ballast)}};
272 # Keep these for later.
278 $results = timethese(-0.1, $code_to_test, 'none');
282 is(ref ($results), 'HASH', "timethese should return a hashref");
283 isa_ok($results->{Foo}, 'Benchmark', "Foo value");
284 isa_ok($results->{Bar}, 'Benchmark', "Bar value");
285 eq_set([keys %$results], [qw(Foo Bar)], 'should be exactly two objects');
286 ok ($foo > 0, "Foo code was run");
287 ok ($bar > 0, "Bar code was run");
289 ok (($end - $start) > 0.1, "benchmarked code ran for over 0.1 seconds");
292 # Remove any warnings about having too few iterations.
293 $got =~ s/\(warning:[^\)]+\)//gs;
294 is ($got =~ tr/ \t\n//c, 0, "format 'none' should suppress output");
296 my $graph_dissassembly =
297 qr!^[ \t]+(\S+)[ \t]+(\w+)[ \t]+(\w+)[ \t]* # Title line
298 \n[ \t]*(\w+)[ \t]+([0-9.]+(?:/s)?)[ \t]+(-+)[ \t]+(-?\d+%)[ \t]*
299 \n[ \t]*(\w+)[ \t]+([0-9.]+(?:/s)?)[ \t]+(-?\d+%)[ \t]+(-+)[ \t]*$!xm;
301 sub check_graph_consistency {
302 my ( $ratetext, $slowc, $fastc,
303 $slowr, $slowratet, $slowslow, $slowfastt,
304 $fastr, $fastratet, $fastslowt, $fastfast)
306 note("calling check_graph_consistency from line " . (caller(1))[2]);
309 &= is ($slowc, $slowr, "left col tag should be top row tag");
311 &= is ($fastc, $fastr, "right col tag should be bottom row tag");
313 like ($slowslow, qr/^-+/, "should be dash for comparing slow with slow");
315 &= is ($slowslow, $fastfast, "slow v slow should be same as fast v fast");
316 my $slowrate = $slowratet;
317 my $fastrate = $fastratet;
318 my ($slow_is_rate, $fast_is_rate);
319 unless ($slow_is_rate = $slowrate =~ s!/s!!) {
320 # Slow is expressed as iters per second.
321 $slowrate = 1/$slowrate if $slowrate;
323 unless ($fast_is_rate = $fastrate =~ s!/s!!) {
324 # Fast is expressed as iters per second.
325 $fastrate = 1/$fastrate if $fastrate;
327 if ($ratetext =~ /rate/i) {
329 &= ok ($slow_is_rate, "slow should be expressed as a rate");
331 &= ok ($fast_is_rate, "fast should be expressed as a rate");
334 ok (!$slow_is_rate, "slow should be expressed as a iters per second");
336 ok (!$fast_is_rate, "fast should be expressed as a iters per second");
339 (my $slowfast = $slowfastt) =~ s!%!!;
340 (my $fastslow = $fastslowt) =~ s!%!!;
341 if ($slowrate < $fastrate) {
342 pass ("slow rate is less than fast rate");
343 unless (ok ($slowfast <= 0 && $slowfast >= -100,
344 "slowfast should be less than or equal to zero, and >= -100")) {
345 print STDERR "# slowfast $slowfast\n";
348 unless (ok ($fastslow > 0, "fastslow should be > 0")) {
349 print STDERR "# fastslow $fastslow\n";
354 &= is ($slowrate, $fastrate,
355 "slow rate isn't less than fast rate, so should be the same");
356 # In OpenBSD the $slowfast is sometimes a really, really, really
357 # small number less than zero, and this gets stringified as -0.
359 &= like ($slowfast, qr/^-?0$/, "slowfast should be zero");
361 &= like ($fastslow, qr/^-?0$/, "fastslow should be zero");
366 sub check_graph_vs_output {
367 my ($chart, $got) = @_;
368 my ( $ratetext, $slowc, $fastc,
369 $slowr, $slowratet, $slowslow, $slowfastt,
370 $fastr, $fastratet, $fastslowt, $fastfast)
371 = $got =~ $graph_dissassembly;
373 = check_graph_consistency ( $ratetext, $slowc, $fastc,
374 $slowr, $slowratet, $slowslow, $slowfastt,
375 $fastr, $fastratet, $fastslowt, $fastfast);
377 &= is_deeply ($chart, [['', $ratetext, $slowc, $fastc],
378 [$slowr, $slowratet, $slowslow, $slowfastt],
379 [$fastr, $fastratet, $fastslowt, $fastfast]],
380 "check the chart layout matches the formatted output");
381 unless ($all_passed) {
382 print STDERR "# Something went wrong there. I got this chart:\n";
383 print STDERR "# $_\n" foreach split /\n/, $got;
388 my ($title, $row1, $row2) = @_;
389 is (scalar @$title, 4, "Four entries in title row");
390 is (scalar @$row1, 4, "Four entries in first row");
391 is (scalar @$row2, 4, "Four entries in second row");
392 is (shift @$title, '', "First entry of output graph should be ''");
393 check_graph_consistency (@$title, @$row1, @$row2);
399 my $chart = cmpthese( -0.1, { a => "++\$i", b => "\$i = sqrt(\$i++)" }, "auto" ) ;
402 ok (($end - $start) > 0.05, "benchmarked code ran for over 0.05 seconds");
405 # Remove any warnings about having too few iterations.
406 $got =~ s/\(warning:[^\)]+\)//gs;
408 like ($got, qr/running\W+a\W+b.*?for at least 0\.1 CPU second/s,
411 $got =~ s/.*\.\.\.//s;
412 like ($got, $Default_Pattern, 'should find default format somewhere');
413 like ($got, $graph_dissassembly, "Should find the output graph somewhere");
414 check_graph_vs_output ($chart, $got);
417 # Not giving auto should suppress timethese results.
421 my $chart = cmpthese( -0.1, { a => "++\$i", b => "\$i = sqrt(\$i++)" } ) ;
424 ok (($end - $start) > 0.05, "benchmarked code ran for over 0.05 seconds");
427 # Remove any warnings about having too few iterations.
428 $got =~ s/\(warning:[^\)]+\)//gs;
430 unlike ($got, qr/running\W+a\W+b.*?for at least 0\.1 CPU second/s,
431 'should not have title');
433 $got =~ s/.*\.\.\.//s;
434 unlike ($got, $Default_Pattern, 'should not find default format somewhere');
435 like ($got, $graph_dissassembly, "Should find the output graph somewhere");
436 check_graph_vs_output ($chart, $got);
442 my $chart = cmpthese( 10, $code_to_test, 'nop' ) ;
444 ok ($foo > 0, "Foo code was run");
445 ok ($bar > 0, "Bar code was run");
448 # Remove any warnings about having too few iterations.
449 $got =~ s/\(warning:[^\)]+\)//gs;
450 like ($got, qr/timing 10 iterations of\s+Bar\W+Foo\W*?\.\.\./s,
453 $got =~ s/.*\.\.\.//s;
454 like ($got, $Nop_Pattern, 'specify format as nop');
455 like ($got, $graph_dissassembly, "Should find the output graph somewhere");
456 check_graph_vs_output ($chart, $got);
462 my $chart = cmpthese( 10, $code_to_test, 'none' ) ;
464 ok ($foo > 0, "Foo code was run");
465 ok ($bar > 0, "Bar code was run");
468 # Remove any warnings about having too few iterations.
469 $got =~ s/\(warning:[^\)]+\)//gs;
470 $got =~ s/^[ \t\n]+//s; # Remove all the whitespace from the beginning
471 is ($got, '', "format 'none' should suppress output");
472 is (ref $chart, 'ARRAY', "output should be an array ref");
473 # Some of these will go bang if the preceding test fails. There will be
474 # a big clue as to why, from the previous test's diagnostic
475 is (ref $chart->[0], 'ARRAY', "output should be an array of arrays");
476 check_graph (@$chart);
482 my $chart = cmpthese( $results ) ;
484 is ($foo, 0, "Foo code was not run");
485 is ($bar, 0, "Bar code was not run");
488 ok ($got !~ /\.\.\./s, 'check that there is no title');
489 like ($got, $graph_dissassembly, "Should find the output graph somewhere");
490 check_graph_vs_output ($chart, $got);
496 my $chart = cmpthese( $results, 'none' ) ;
498 is ($foo, 0, "Foo code was not run");
499 is ($bar, 0, "Bar code was not run");
502 is ($got, '', "'none' should suppress all output");
503 is (ref $chart, 'ARRAY', "output should be an array ref");
504 # Some of these will go bang if the preceding test fails. There will be
505 # a big clue as to why, from the previous test's diagnostic
506 is (ref $chart->[0], 'ARRAY', "output should be an array of arrays");
507 check_graph (@$chart);
510 ###}my $out = tie *OUT, 'TieOut'; my ($got); ###
512 my $debug = tie *STDERR, 'TieOut';
515 isa_ok(timeit(5, '++$bar'), 'Benchmark', "timeit eval");
516 is ($bar, 5, "benchmarked code was run 5 times");
517 is ($debug->read(), '', "There was no debug output");
523 $got = timeit(5, '++$bar');
525 isa_ok($got, 'Benchmark', "timeit eval");
526 is ($bar, 5, "benchmarked code was run 5 times");
527 is ($out->read(), '', "There was no STDOUT output with debug enabled");
528 isnt ($debug->read(), '', "There was STDERR debug output with debug enabled");
533 isa_ok(timeit(5, '++$bar'), 'Benchmark', "timeit eval");
534 is ($bar, 5, "benchmarked code was run 5 times");
535 is ($debug->read(), '', "There was no debug output debug disabled");
540 # To check the cache we are poking where we don't belong, inside the namespace.
541 # The way benchmark is written we can't actually check whether the cache is
542 # being used, merely what's become cached.
545 my @before_keys = keys %Benchmark::Cache;
547 isa_ok(timeit(5, '++$bar'), 'Benchmark', "timeit eval");
548 is ($bar, 5, "benchmarked code was run 5 times");
549 my @after5_keys = keys %Benchmark::Cache;
551 isa_ok(timeit(10, '++$bar'), 'Benchmark', "timeit eval");
552 is ($bar, 10, "benchmarked code was run 10 times");
553 ok (!eq_array ([keys %Benchmark::Cache], \@after5_keys), "10 differs from 5");
556 # Hash key order will be the same if there are the same keys.
557 is_deeply ([keys %Benchmark::Cache], \@after5_keys,
558 "cleared 10, only cached results for 5 should remain");
561 is_deeply ([keys %Benchmark::Cache], \@before_keys,
562 "back to square 1 when we clear the cache again?");
565 { # Check usage error messages
566 my %usage = %Benchmark::_Usage;
567 delete $usage{runloop}; # not public, not worrying about it just now
569 my @takes_no_args = qw(clearallcache disablecache enablecache);
571 my %cmpthese = ('forgot {}' => 'cmpthese( 42, foo => sub { 1 } )',
572 'not result' => 'cmpthese(42)',
573 'array ref' => 'cmpthese( 42, [ foo => sub { 1 } ] )',
575 while( my($name, $code) = each %cmpthese ) {
577 is( $@, $usage{cmpthese}, "cmpthese usage: $name" );
580 my %timethese = ('forgot {}' => 'timethese( 42, foo => sub { 1 } )',
581 'no code' => 'timethese(42)',
582 'array ref' => 'timethese( 42, [ foo => sub { 1 } ] )',
585 while( my($name, $code) = each %timethese ) {
587 is( $@, $usage{timethese}, "timethese usage: $name" );
591 while( my($func, $usage) = each %usage ) {
592 next if grep $func eq $_, @takes_no_args;
594 is( $@, $usage, "$func usage: no args" );
597 foreach my $func (@takes_no_args) {
599 is( $@, $usage{$func}, "$func usage: with args" );
608 bless(\( my $ref = ''), $class);
613 $$self .= join('', @_);
618 $$self .= sprintf shift, @_;
623 return substr($$self, 0, length($$self), '');