This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Benchmark.t: note line# of check_graph_consistency
[perl5.git] / lib / Benchmark.t
CommitLineData
0e74ff8e
JH
1#!./perl -w
2
3BEGIN {
4 chdir 't' if -d 't';
53aa2791 5 @INC = ('../lib');
0e74ff8e
JH
6}
7
8use warnings;
9use strict;
10use vars qw($foo $bar $baz $ballast);
d684718b 11use Test::More tests => 196;
0e74ff8e
JH
12
13use Benchmark qw(:all);
14
ab43e786 15my $delta = 0.4;
0e74ff8e
JH
16
17# Some timing ballast
18sub fib {
19 my $n = shift;
20 return $n if $n < 2;
21 fib($n-1) + fib($n-2);
22}
23$ballast = 15;
24
53aa2791 25my $All_Pattern =
0e74ff8e 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\)/;
53aa2791 27my $Noc_Pattern =
0e74ff8e 28 qr/(\d+) +wallclock secs? +\( *(-?\d+\.\d\d) +usr +\+ +(-?\d+\.\d\d) +sys += +(-?\d+\.\d\d) +CPU\)/;
53aa2791 29my $Nop_Pattern =
0e74ff8e 30 qr/(\d+) +wallclock secs? +\( *(-?\d+\.\d\d) +cusr +\+ +(-?\d+\.\d\d) +csys += +\d+\.\d\d +CPU\)/;
98dc9551 31# Please don't trust the matching parentheses to be useful in this :-)
53aa2791 32my $Default_Pattern = qr/$All_Pattern|$Noc_Pattern/;
0e74ff8e
JH
33
34my $t0 = new Benchmark;
35isa_ok ($t0, 'Benchmark', "Ensure we can create a benchmark object");
36
37# We use the benchmark object once we've done some work:
38
39isa_ok(timeit(5, sub {++$foo}), 'Benchmark', "timeit CODEREF");
40is ($foo, 5, "benchmarked code was run 5 times");
41
42isa_ok(timeit(5, '++$bar'), 'Benchmark', "timeit eval");
43is ($bar, 5, "benchmarked code was run 5 times");
44
f265d4df
AS
45# is coderef called with spurious arguments?
46timeit( 1, sub { $foo = @_ });
47is ($foo, 0, "benchmarked code called without arguments");
48
49
0e74ff8e
JH
50print "# Burning CPU to benchmark things will take time...\n";
51
52
53
54# We need to do something fairly slow in the coderef.
55# Same coderef. Same place in memory.
56my $coderef = sub {$baz += fib($ballast)};
57
58# The default is three.
59$baz = 0;
60my $threesecs = countit(0, $coderef);
61isa_ok($threesecs, 'Benchmark', "countit 0, CODEREF");
62isnt ($baz, 0, "benchmarked code was run");
63my $in_threesecs = $threesecs->iters;
d684718b 64print "# in_threesecs=$in_threesecs iterations\n";
0e74ff8e 65ok ($in_threesecs > 0, "iters returned positive iterations");
d684718b
DM
66my $cpu = $threesecs->[1] + $threesecs->[2]; # user + sys
67cmp_ok($cpu, '>=', 3.0, "3s cpu is at least 3s");
68$in_threesecs *= (3/$cpu); # adjust because may not have run for exactly 3s
69print "# in_threesecs=$in_threesecs adjusted iterations\n";
0e74ff8e 70
95d5be9e 71my $estimate = int (100 * $in_threesecs / 3) / 100;
0e74ff8e
JH
72print "# from the 3 second run estimate $estimate iterations in 1 second...\n";
73$baz = 0;
74my $onesec = countit(1, $coderef);
75isa_ok($onesec, 'Benchmark', "countit 1, CODEREF");
76isnt ($baz, 0, "benchmarked code was run");
77my $in_onesec = $onesec->iters;
d684718b 78print "# in_onesec=$in_onesec iterations\n";
0e74ff8e 79ok ($in_onesec > 0, "iters returned positive iterations");
d684718b
DM
80$cpu = $onesec->[1] + $onesec->[2]; # user + sys
81cmp_ok($cpu, '>=', 1.0, "1s cpu is at least 1s");
82$in_onesec *= (1/$cpu); # adjust because may not have run for exactly 1s
83print "# in_onesec=$in_onesec adjusted iterations\n";
0e74ff8e 84
ab43e786
NC
85{
86 my $difference = $in_onesec - $estimate;
87 my $actual = abs ($difference / $in_onesec);
8350df42
TR
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.");
ab43e786 90}
0e74ff8e
JH
91
92# I found that the eval'ed version was 3 times faster than the coderef.
93# (now it has a different ballast value)
94$baz = 0;
95my $again = countit(1, '$baz += fib($ballast)');
96isa_ok($onesec, 'Benchmark', "countit 1, eval");
97isnt ($baz, 0, "benchmarked code was run");
98my $in_again = $again->iters;
99print "# $in_again iterations\n";
100ok ($in_again > 0, "iters returned positive iterations");
101
102
103my $t1 = new Benchmark;
104isa_ok ($t1, 'Benchmark', "Create another benchmark object now we're finished");
105
106my $diff = timediff ($t1, $t0);
107isa_ok ($diff, 'Benchmark', "Get the time difference");
108isa_ok (timesum ($t0, $t1), 'Benchmark', "check timesum");
109
110my $default = timestr ($diff);
111isnt ($default, '', 'timestr ($diff)');
112my $auto = timestr ($diff, 'auto');
113is ($auto, $default, 'timestr ($diff, "auto") matches timestr ($diff)');
114
115{
116 my $all = timestr ($diff, 'all');
53aa2791 117 like ($all, $All_Pattern, 'timestr ($diff, "all")');
0e74ff8e
JH
118 print "# $all\n";
119
53aa2791 120 my ($wallclock, $usr, $sys, $cusr, $csys, $cpu) = $all =~ $All_Pattern;
0e74ff8e 121
98dc9551 122 is (timestr ($diff, 'none'), '', "none suppresses output");
0e74ff8e
JH
123
124 my $noc = timestr ($diff, 'noc');
125 like ($noc, qr/$wallclock +wallclock secs? +\( *$usr +usr +\+ +$sys +sys += +$cpu +CPU\)/, 'timestr ($diff, "noc")');
126
127 my $nop = timestr ($diff, 'nop');
128 like ($nop, qr/$wallclock +wallclock secs? +\( *$cusr +cusr +\+ +$csys +csys += +\d+\.\d\d +CPU\)/, 'timestr ($diff, "nop")');
129
130 if ($auto eq $noc) {
131 pass ('"auto" is "noc"');
132 } else {
133 is ($auto, $all, '"auto" isn\'t "noc", so should be eq to "all"');
134 }
135
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"]');
138}
139
140my $out = tie *OUT, 'TieOut';
141
142my $iterations = 3;
143
144$foo = 0;
145select(OUT);
146my $got = timethis($iterations, sub {++$foo});
147select(STDOUT);
148isa_ok($got, 'Benchmark', "timethis CODEREF");
149is ($foo, $iterations, "benchmarked code was run $iterations times");
150
151$got = $out->read();
152like ($got, qr/^timethis $iterations/, 'default title');
53aa2791 153like ($got, $Default_Pattern, 'default format is all or noc');
0e74ff8e
JH
154
155$bar = 0;
156select(OUT);
157$got = timethis($iterations, '++$bar');
158select(STDOUT);
159isa_ok($got, 'Benchmark', "timethis eval");
160is ($bar, $iterations, "benchmarked code was run $iterations times");
161
162$got = $out->read();
163like ($got, qr/^timethis $iterations/, 'default title');
53aa2791 164like ($got, $Default_Pattern, 'default format is all or noc');
0e74ff8e
JH
165
166my $title = 'lies, damn lies and benchmarks';
167$foo = 0;
168select(OUT);
169$got = timethis($iterations, sub {++$foo}, $title);
170select(STDOUT);
171isa_ok($got, 'Benchmark', "timethis with title");
172is ($foo, $iterations, "benchmarked code was run $iterations times");
173
174$got = $out->read();
175like ($got, qr/^$title:/, 'specify title');
53aa2791 176like ($got, $Default_Pattern, 'default format is all or noc');
0e74ff8e
JH
177
178# default is auto, which is all or noc. nop can never match the default
179$foo = 0;
180select(OUT);
181$got = timethis($iterations, sub {++$foo}, $title, 'nop');
182select(STDOUT);
183isa_ok($got, 'Benchmark', "timethis with format");
184is ($foo, $iterations, "benchmarked code was run $iterations times");
185
186$got = $out->read();
187like ($got, qr/^$title:/, 'specify title');
53aa2791 188like ($got, $Nop_Pattern, 'specify format as nop');
0e74ff8e
JH
189
190{
191 $foo = 0;
192 select(OUT);
193 my $start = time;
194 $got = timethis(-2, sub {$foo+= fib($ballast)}, $title, 'none');
195 my $end = time;
196 select(STDOUT);
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");
201
202 $got = $out->read();
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
206
207 is ($got, '', "format 'none' should suppress output");
208}
209
210$foo = $bar = $baz = 0;
211select(OUT);
212$got = timethese($iterations, { Foo => sub {++$foo}, Bar => '++$bar',
213 Baz => sub {++$baz} });
214select(STDOUT);
215is(ref ($got), 'HASH', "timethese should return a hashref");
216isa_ok($got->{Foo}, 'Benchmark', "Foo value");
217isa_ok($got->{Bar}, 'Benchmark', "Bar value");
218isa_ok($got->{Baz}, 'Benchmark', "Baz value");
219eq_set([keys %$got], [qw(Foo Bar Baz)], 'should be exactly three objects');
220is ($foo, $iterations, "Foo code was run $iterations times");
221is ($bar, $iterations, "Bar code was run $iterations times");
222is ($baz, $iterations, "Baz code was run $iterations times");
223
224$got = $out->read();
225# Remove any warnings about having too few iterations.
226$got =~ s/\(warning:[^\)]+\)//gs;
227
228like ($got, qr/timing $iterations iterations of\s+Bar\W+Baz\W+Foo\W*?\.\.\./s,
229 'check title');
230# Remove the title
231$got =~ s/.*\.\.\.//s;
232like ($got, qr/\bBar\b.*\bBaz\b.*\bFoo\b/s, 'check output is in sorted order');
53aa2791
MS
233like ($got, $Default_Pattern, 'should find default format somewhere');
234
235
236{ # ensure 'use strict' does not leak from Benchmark.pm into benchmarked code
237 no strict;
238 select OUT;
239
240 eval {
241 timethese( 1,
242 { undeclared_var => q{ $i++; $i-- },
243 symbolic_ref => q{ $bar = 42;
244 $foo = 'bar';
245 $q = ${$foo} },
246 },
247 'none'
248 );
249
250 };
251 is( $@, '', q{no strict leakage in name => 'code'} );
252
253 eval {
254 timethese( 1,
255 { undeclared_var => sub { $i++; $i-- },
256 symbolic_ref => sub { $bar = 42;
257 $foo = 'bar';
258 return ${$foo} },
259 },
260 'none'
261 );
262 };
263 is( $@, '', q{no strict leakage in name => sub { code }} );
264
265 # clear out buffer
266 $out->read;
267}
268
0e74ff8e
JH
269
270my $code_to_test = { Foo => sub {$foo+=fib($ballast-2)},
271 Bar => sub {$bar+=fib($ballast)}};
272# Keep these for later.
273my $results;
274{
275 $foo = $bar = 0;
276 select(OUT);
277 my $start = times;
278 $results = timethese(-0.1, $code_to_test, 'none');
279 my $end = times;
280 select(STDOUT);
281
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");
288
289 ok (($end - $start) > 0.1, "benchmarked code ran for over 0.1 seconds");
290
291 $got = $out->read();
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");
295}
296my $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;
300
301sub check_graph_consistency {
302 my ( $ratetext, $slowc, $fastc,
303 $slowr, $slowratet, $slowslow, $slowfastt,
304 $fastr, $fastratet, $fastslowt, $fastfast)
305 = @_;
ca55f232 306 note("calling check_graph_consistency from line " . (caller(1))[2]);
23c50b23
NC
307 my $all_passed = 1;
308 $all_passed
309 &= is ($slowc, $slowr, "left col tag should be top row tag");
310 $all_passed
311 &= is ($fastc, $fastr, "right col tag should be bottom row tag");
312 $all_passed &=
313 like ($slowslow, qr/^-+/, "should be dash for comparing slow with slow");
314 $all_passed
315 &= is ($slowslow, $fastfast, "slow v slow should be same as fast v fast");
0e74ff8e
JH
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;
322 }
323 unless ($fast_is_rate = $fastrate =~ s!/s!!) {
324 # Fast is expressed as iters per second.
325 $fastrate = 1/$fastrate if $fastrate;
326 }
327 if ($ratetext =~ /rate/i) {
23c50b23
NC
328 $all_passed
329 &= ok ($slow_is_rate, "slow should be expressed as a rate");
330 $all_passed
331 &= ok ($fast_is_rate, "fast should be expressed as a rate");
0e74ff8e 332 } else {
23c50b23
NC
333 $all_passed &=
334 ok (!$slow_is_rate, "slow should be expressed as a iters per second");
335 $all_passed &=
336 ok (!$fast_is_rate, "fast should be expressed as a iters per second");
0e74ff8e
JH
337 }
338
339 (my $slowfast = $slowfastt) =~ s!%!!;
340 (my $fastslow = $fastslowt) =~ s!%!!;
341 if ($slowrate < $fastrate) {
342 pass ("slow rate is less than fast rate");
07e88136
JH
343 unless (ok ($slowfast <= 0 && $slowfast >= -100,
344 "slowfast should be less than or equal to zero, and >= -100")) {
2d684b7a 345 print STDERR "# slowfast $slowfast\n";
23c50b23
NC
346 $all_passed = 0;
347 }
348 unless (ok ($fastslow > 0, "fastslow should be > 0")) {
e5967bfd 349 print STDERR "# fastslow $fastslow\n";
23c50b23
NC
350 $all_passed = 0;
351 }
0e74ff8e 352 } else {
23c50b23
NC
353 $all_passed
354 &= is ($slowrate, $fastrate,
355 "slow rate isn't less than fast rate, so should be the same");
620b59a5
JH
356 # In OpenBSD the $slowfast is sometimes a really, really, really
357 # small number less than zero, and this gets stringified as -0.
23c50b23 358 $all_passed
620b59a5 359 &= like ($slowfast, qr/^-?0$/, "slowfast should be zero");
23c50b23 360 $all_passed
620b59a5 361 &= like ($fastslow, qr/^-?0$/, "fastslow should be zero");
0e74ff8e 362 }
23c50b23 363 return $all_passed;
0e74ff8e
JH
364}
365
366sub 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;
23c50b23
NC
372 my $all_passed
373 = check_graph_consistency ( $ratetext, $slowc, $fastc,
374 $slowr, $slowratet, $slowslow, $slowfastt,
375 $fastr, $fastratet, $fastslowt, $fastfast);
376 $all_passed
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;
384 }
0e74ff8e
JH
385}
386
387sub check_graph {
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);
394}
395
396{
397 select(OUT);
398 my $start = times;
8962dfd6 399 my $chart = cmpthese( -0.1, { a => "++\$i", b => "\$i = sqrt(\$i++)" }, "auto" ) ;
0e74ff8e
JH
400 my $end = times;
401 select(STDOUT);
402 ok (($end - $start) > 0.05, "benchmarked code ran for over 0.05 seconds");
403
404 $got = $out->read();
405 # Remove any warnings about having too few iterations.
406 $got =~ s/\(warning:[^\)]+\)//gs;
407
408 like ($got, qr/running\W+a\W+b.*?for at least 0\.1 CPU second/s,
409 'check title');
410 # Remove the title
411 $got =~ s/.*\.\.\.//s;
53aa2791 412 like ($got, $Default_Pattern, 'should find default format somewhere');
0e74ff8e
JH
413 like ($got, $graph_dissassembly, "Should find the output graph somewhere");
414 check_graph_vs_output ($chart, $got);
415}
416
8962dfd6
A
417# Not giving auto should suppress timethese results.
418{
419 select(OUT);
420 my $start = times;
421 my $chart = cmpthese( -0.1, { a => "++\$i", b => "\$i = sqrt(\$i++)" } ) ;
422 my $end = times;
423 select(STDOUT);
424 ok (($end - $start) > 0.05, "benchmarked code ran for over 0.05 seconds");
425
426 $got = $out->read();
427 # Remove any warnings about having too few iterations.
428 $got =~ s/\(warning:[^\)]+\)//gs;
429
430 unlike ($got, qr/running\W+a\W+b.*?for at least 0\.1 CPU second/s,
431 'should not have title');
432 # Remove the title
433 $got =~ s/.*\.\.\.//s;
53aa2791 434 unlike ($got, $Default_Pattern, 'should not find default format somewhere');
8962dfd6
A
435 like ($got, $graph_dissassembly, "Should find the output graph somewhere");
436 check_graph_vs_output ($chart, $got);
437}
438
0e74ff8e
JH
439{
440 $foo = $bar = 0;
441 select(OUT);
442 my $chart = cmpthese( 10, $code_to_test, 'nop' ) ;
443 select(STDOUT);
444 ok ($foo > 0, "Foo code was run");
445 ok ($bar > 0, "Bar code was run");
446
447 $got = $out->read();
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,
451 'check title');
452 # Remove the title
453 $got =~ s/.*\.\.\.//s;
53aa2791 454 like ($got, $Nop_Pattern, 'specify format as nop');
0e74ff8e
JH
455 like ($got, $graph_dissassembly, "Should find the output graph somewhere");
456 check_graph_vs_output ($chart, $got);
457}
458
459{
460 $foo = $bar = 0;
461 select(OUT);
462 my $chart = cmpthese( 10, $code_to_test, 'none' ) ;
463 select(STDOUT);
464 ok ($foo > 0, "Foo code was run");
465 ok ($bar > 0, "Bar code was run");
466
467 $got = $out->read();
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);
477}
478
479{
480 $foo = $bar = 0;
481 select(OUT);
482 my $chart = cmpthese( $results ) ;
483 select(STDOUT);
484 is ($foo, 0, "Foo code was not run");
485 is ($bar, 0, "Bar code was not run");
486
487 $got = $out->read();
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);
491}
492
493{
494 $foo = $bar = 0;
495 select(OUT);
496 my $chart = cmpthese( $results, 'none' ) ;
497 select(STDOUT);
498 is ($foo, 0, "Foo code was not run");
499 is ($bar, 0, "Bar code was not run");
500
501 $got = $out->read();
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);
508}
509
510###}my $out = tie *OUT, 'TieOut'; my ($got); ###
511
512my $debug = tie *STDERR, 'TieOut';
513
514$bar = 0;
515isa_ok(timeit(5, '++$bar'), 'Benchmark', "timeit eval");
516is ($bar, 5, "benchmarked code was run 5 times");
517is ($debug->read(), '', "There was no debug output");
518
519Benchmark->debug(1);
520
521$bar = 0;
522select(OUT);
523$got = timeit(5, '++$bar');
524select(STDOUT);
525isa_ok($got, 'Benchmark', "timeit eval");
526is ($bar, 5, "benchmarked code was run 5 times");
527is ($out->read(), '', "There was no STDOUT output with debug enabled");
528isnt ($debug->read(), '', "There was STDERR debug output with debug enabled");
529
530Benchmark->debug(0);
531
532$bar = 0;
533isa_ok(timeit(5, '++$bar'), 'Benchmark', "timeit eval");
534is ($bar, 5, "benchmarked code was run 5 times");
535is ($debug->read(), '', "There was no debug output debug disabled");
536
537undef $debug;
538untie *STDERR;
539
540# To check the cache we are poking where we don't belong, inside the namespace.
98dc9551 541# The way benchmark is written we can't actually check whether the cache is
0e74ff8e
JH
542# being used, merely what's become cached.
543
544clearallcache();
53aa2791 545my @before_keys = keys %Benchmark::Cache;
0e74ff8e
JH
546$bar = 0;
547isa_ok(timeit(5, '++$bar'), 'Benchmark', "timeit eval");
548is ($bar, 5, "benchmarked code was run 5 times");
53aa2791 549my @after5_keys = keys %Benchmark::Cache;
0e74ff8e
JH
550$bar = 0;
551isa_ok(timeit(10, '++$bar'), 'Benchmark', "timeit eval");
552is ($bar, 10, "benchmarked code was run 10 times");
53aa2791 553ok (!eq_array ([keys %Benchmark::Cache], \@after5_keys), "10 differs from 5");
0e74ff8e
JH
554
555clearcache(10);
556# Hash key order will be the same if there are the same keys.
53aa2791 557is_deeply ([keys %Benchmark::Cache], \@after5_keys,
0e74ff8e
JH
558 "cleared 10, only cached results for 5 should remain");
559
560clearallcache();
53aa2791 561is_deeply ([keys %Benchmark::Cache], \@before_keys,
0e74ff8e
JH
562 "back to square 1 when we clear the cache again?");
563
564
53aa2791
MS
565{ # Check usage error messages
566 my %usage = %Benchmark::_Usage;
567 delete $usage{runloop}; # not public, not worrying about it just now
568
569 my @takes_no_args = qw(clearallcache disablecache enablecache);
570
571 my %cmpthese = ('forgot {}' => 'cmpthese( 42, foo => sub { 1 } )',
572 'not result' => 'cmpthese(42)',
573 'array ref' => 'cmpthese( 42, [ foo => sub { 1 } ] )',
574 );
575 while( my($name, $code) = each %cmpthese ) {
576 eval $code;
577 is( $@, $usage{cmpthese}, "cmpthese usage: $name" );
578 }
579
580 my %timethese = ('forgot {}' => 'timethese( 42, foo => sub { 1 } )',
581 'no code' => 'timethese(42)',
582 'array ref' => 'timethese( 42, [ foo => sub { 1 } ] )',
583 );
584
585 while( my($name, $code) = each %timethese ) {
586 eval $code;
587 is( $@, $usage{timethese}, "timethese usage: $name" );
588 }
589
590
591 while( my($func, $usage) = each %usage ) {
592 next if grep $func eq $_, @takes_no_args;
593 eval "$func()";
594 is( $@, $usage, "$func usage: no args" );
595 }
596
597 foreach my $func (@takes_no_args) {
598 eval "$func(42)";
f695f0e6 599 is( $@, $usage{$func}, "$func usage: with args" );
53aa2791
MS
600 }
601}
602
603
0e74ff8e
JH
604package TieOut;
605
606sub TIEHANDLE {
607 my $class = shift;
608 bless(\( my $ref = ''), $class);
609}
610
611sub PRINT {
612 my $self = shift;
613 $$self .= join('', @_);
614}
615
616sub PRINTF {
617 my $self = shift;
618 $$self .= sprintf shift, @_;
619}
620
621sub read {
622 my $self = shift;
623 return substr($$self, 0, length($$self), '');
624}