Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

798 lines
22 KiB

  1. package Benchmark;
  2. =head1 NAME
  3. Benchmark - benchmark running times of Perl code
  4. =head1 SYNOPSIS
  5. timethis ($count, "code");
  6. # Use Perl code in strings...
  7. timethese($count, {
  8. 'Name1' => '...code1...',
  9. 'Name2' => '...code2...',
  10. });
  11. # ... or use subroutine references.
  12. timethese($count, {
  13. 'Name1' => sub { ...code1... },
  14. 'Name2' => sub { ...code2... },
  15. });
  16. # cmpthese can be used both ways as well
  17. cmpthese($count, {
  18. 'Name1' => '...code1...',
  19. 'Name2' => '...code2...',
  20. });
  21. cmpthese($count, {
  22. 'Name1' => sub { ...code1... },
  23. 'Name2' => sub { ...code2... },
  24. });
  25. # ...or in two stages
  26. $results = timethese($count,
  27. {
  28. 'Name1' => sub { ...code1... },
  29. 'Name2' => sub { ...code2... },
  30. },
  31. 'none'
  32. );
  33. cmpthese( $results ) ;
  34. $t = timeit($count, '...other code...')
  35. print "$count loops of other code took:",timestr($t),"\n";
  36. $t = countit($time, '...other code...')
  37. $count = $t->iters ;
  38. print "$count loops of other code took:",timestr($t),"\n";
  39. =head1 DESCRIPTION
  40. The Benchmark module encapsulates a number of routines to help you
  41. figure out how long it takes to execute some code.
  42. timethis - run a chunk of code several times
  43. timethese - run several chunks of code several times
  44. cmpthese - print results of timethese as a comparison chart
  45. timeit - run a chunk of code and see how long it goes
  46. countit - see how many times a chunk of code runs in a given time
  47. =head2 Methods
  48. =over 10
  49. =item new
  50. Returns the current time. Example:
  51. use Benchmark;
  52. $t0 = new Benchmark;
  53. # ... your code here ...
  54. $t1 = new Benchmark;
  55. $td = timediff($t1, $t0);
  56. print "the code took:",timestr($td),"\n";
  57. =item debug
  58. Enables or disable debugging by setting the C<$Benchmark::Debug> flag:
  59. debug Benchmark 1;
  60. $t = timeit(10, ' 5 ** $Global ');
  61. debug Benchmark 0;
  62. =item iters
  63. Returns the number of iterations.
  64. =back
  65. =head2 Standard Exports
  66. The following routines will be exported into your namespace
  67. if you use the Benchmark module:
  68. =over 10
  69. =item timeit(COUNT, CODE)
  70. Arguments: COUNT is the number of times to run the loop, and CODE is
  71. the code to run. CODE may be either a code reference or a string to
  72. be eval'd; either way it will be run in the caller's package.
  73. Returns: a Benchmark object.
  74. =item timethis ( COUNT, CODE, [ TITLE, [ STYLE ]] )
  75. Time COUNT iterations of CODE. CODE may be a string to eval or a
  76. code reference; either way the CODE will run in the caller's package.
  77. Results will be printed to STDOUT as TITLE followed by the times.
  78. TITLE defaults to "timethis COUNT" if none is provided. STYLE
  79. determines the format of the output, as described for timestr() below.
  80. The COUNT can be zero or negative: this means the I<minimum number of
  81. CPU seconds> to run. A zero signifies the default of 3 seconds. For
  82. example to run at least for 10 seconds:
  83. timethis(-10, $code)
  84. or to run two pieces of code tests for at least 3 seconds:
  85. timethese(0, { test1 => '...', test2 => '...'})
  86. CPU seconds is, in UNIX terms, the user time plus the system time of
  87. the process itself, as opposed to the real (wallclock) time and the
  88. time spent by the child processes. Less than 0.1 seconds is not
  89. accepted (-0.01 as the count, for example, will cause a fatal runtime
  90. exception).
  91. Note that the CPU seconds is the B<minimum> time: CPU scheduling and
  92. other operating system factors may complicate the attempt so that a
  93. little bit more time is spent. The benchmark output will, however,
  94. also tell the number of C<$code> runs/second, which should be a more
  95. interesting number than the actually spent seconds.
  96. Returns a Benchmark object.
  97. =item timethese ( COUNT, CODEHASHREF, [ STYLE ] )
  98. The CODEHASHREF is a reference to a hash containing names as keys
  99. and either a string to eval or a code reference for each value.
  100. For each (KEY, VALUE) pair in the CODEHASHREF, this routine will
  101. call
  102. timethis(COUNT, VALUE, KEY, STYLE)
  103. The routines are called in string comparison order of KEY.
  104. The COUNT can be zero or negative, see timethis().
  105. Returns a hash of Benchmark objects, keyed by name.
  106. =item timediff ( T1, T2 )
  107. Returns the difference between two Benchmark times as a Benchmark
  108. object suitable for passing to timestr().
  109. =item timestr ( TIMEDIFF, [ STYLE, [ FORMAT ] ] )
  110. Returns a string that formats the times in the TIMEDIFF object in
  111. the requested STYLE. TIMEDIFF is expected to be a Benchmark object
  112. similar to that returned by timediff().
  113. STYLE can be any of 'all', 'none', 'noc', 'nop' or 'auto'. 'all' shows
  114. each of the 5 times available ('wallclock' time, user time, system time,
  115. user time of children, and system time of children). 'noc' shows all
  116. except the two children times. 'nop' shows only wallclock and the
  117. two children times. 'auto' (the default) will act as 'all' unless
  118. the children times are both zero, in which case it acts as 'noc'.
  119. 'none' prevents output.
  120. FORMAT is the L<printf(3)>-style format specifier (without the
  121. leading '%') to use to print the times. It defaults to '5.2f'.
  122. =back
  123. =head2 Optional Exports
  124. The following routines will be exported into your namespace
  125. if you specifically ask that they be imported:
  126. =over 10
  127. =item clearcache ( COUNT )
  128. Clear the cached time for COUNT rounds of the null loop.
  129. =item clearallcache ( )
  130. Clear all cached times.
  131. =item cmpthese ( COUT, CODEHASHREF, [ STYLE ] )
  132. =item cmpthese ( RESULTSHASHREF )
  133. Optionally calls timethese(), then outputs comparison chart. This
  134. chart is sorted from slowest to fastest, and shows the percent
  135. speed difference between each pair of tests. Can also be passed
  136. the data structure that timethese() returns:
  137. $results = timethese( .... );
  138. cmpthese( $results );
  139. Returns the data structure returned by timethese() (or passed in).
  140. =item countit(TIME, CODE)
  141. Arguments: TIME is the minimum length of time to run CODE for, and CODE is
  142. the code to run. CODE may be either a code reference or a string to
  143. be eval'd; either way it will be run in the caller's package.
  144. TIME is I<not> negative. countit() will run the loop many times to
  145. calculate the speed of CODE before running it for TIME. The actual
  146. time run for will usually be greater than TIME due to system clock
  147. resolution, so it's best to look at the number of iterations divided
  148. by the times that you are concerned with, not just the iterations.
  149. Returns: a Benchmark object.
  150. =item disablecache ( )
  151. Disable caching of timings for the null loop. This will force Benchmark
  152. to recalculate these timings for each new piece of code timed.
  153. =item enablecache ( )
  154. Enable caching of timings for the null loop. The time taken for COUNT
  155. rounds of the null loop will be calculated only once for each
  156. different COUNT used.
  157. =item timesum ( T1, T2 )
  158. Returns the sum of two Benchmark times as a Benchmark object suitable
  159. for passing to timestr().
  160. =back
  161. =head1 NOTES
  162. The data is stored as a list of values from the time and times
  163. functions:
  164. ($real, $user, $system, $children_user, $children_system, $iters)
  165. in seconds for the whole loop (not divided by the number of rounds).
  166. The timing is done using time(3) and times(3).
  167. Code is executed in the caller's package.
  168. The time of the null loop (a loop with the same
  169. number of rounds but empty loop body) is subtracted
  170. from the time of the real loop.
  171. The null loop times can be cached, the key being the
  172. number of rounds. The caching can be controlled using
  173. calls like these:
  174. clearcache($key);
  175. clearallcache();
  176. disablecache();
  177. enablecache();
  178. Caching is off by default, as it can (usually slightly) decrease
  179. accuracy and does not usually noticably affect runtimes.
  180. =head1 EXAMPLES
  181. For example,
  182. use Benchmark;$x=3;cmpthese(-5,{a=>sub{$x*$x},b=>sub{$x**2}})
  183. outputs something like this:
  184. Benchmark: running a, b, each for at least 5 CPU seconds...
  185. a: 10 wallclock secs ( 5.14 usr + 0.13 sys = 5.27 CPU) @ 3835055.60/s (n=20210743)
  186. b: 5 wallclock secs ( 5.41 usr + 0.00 sys = 5.41 CPU) @ 1574944.92/s (n=8520452)
  187. Rate b a
  188. b 1574945/s -- -59%
  189. a 3835056/s 144% --
  190. while
  191. use Benchmark;
  192. $x=3;
  193. $r=timethese(-5,{a=>sub{$x*$x},b=>sub{$x**2}},'none');
  194. cmpthese($r);
  195. outputs something like this:
  196. Rate b a
  197. b 1559428/s -- -62%
  198. a 4152037/s 166% --
  199. =head1 INHERITANCE
  200. Benchmark inherits from no other class, except of course
  201. for Exporter.
  202. =head1 CAVEATS
  203. Comparing eval'd strings with code references will give you
  204. inaccurate results: a code reference will show a slightly slower
  205. execution time than the equivalent eval'd string.
  206. The real time timing is done using time(2) and
  207. the granularity is therefore only one second.
  208. Short tests may produce negative figures because perl
  209. can appear to take longer to execute the empty loop
  210. than a short test; try:
  211. timethis(100,'1');
  212. The system time of the null loop might be slightly
  213. more than the system time of the loop with the actual
  214. code and therefore the difference might end up being E<lt> 0.
  215. =head1 SEE ALSO
  216. L<Devel::DProf> - a Perl code profiler
  217. =head1 AUTHORS
  218. Jarkko Hietaniemi <F<[email protected]>>, Tim Bunce <F<[email protected]>>
  219. =head1 MODIFICATION HISTORY
  220. September 8th, 1994; by Tim Bunce.
  221. March 28th, 1997; by Hugo van der Sanden: added support for code
  222. references and the already documented 'debug' method; revamped
  223. documentation.
  224. April 04-07th, 1997: by Jarkko Hietaniemi, added the run-for-some-time
  225. functionality.
  226. September, 1999; by Barrie Slaymaker: math fixes and accuracy and
  227. efficiency tweaks. Added cmpthese(). A result is now returned from
  228. timethese(). Exposed countit() (was runfor()).
  229. =cut
  230. # evaluate something in a clean lexical environment
  231. sub _doeval { eval shift }
  232. #
  233. # put any lexicals at file scope AFTER here
  234. #
  235. use Carp;
  236. use Exporter;
  237. @ISA=(Exporter);
  238. @EXPORT=qw(timeit timethis timethese timediff timestr);
  239. @EXPORT_OK=qw(timesum cmpthese countit
  240. clearcache clearallcache disablecache enablecache);
  241. $VERSION = 1.00;
  242. &init;
  243. sub init {
  244. $debug = 0;
  245. $min_count = 4;
  246. $min_cpu = 0.4;
  247. $defaultfmt = '5.2f';
  248. $defaultstyle = 'auto';
  249. # The cache can cause a slight loss of sys time accuracy. If a
  250. # user does many tests (>10) with *very* large counts (>10000)
  251. # or works on a very slow machine the cache may be useful.
  252. &disablecache;
  253. &clearallcache;
  254. }
  255. sub debug { $debug = ($_[1] != 0); }
  256. # The cache needs two branches: 's' for strings and 'c' for code. The
  257. # emtpy loop is different in these two cases.
  258. sub clearcache { delete $cache{"$_[0]c"}; delete $cache{"$_[0]s"}; }
  259. sub clearallcache { %cache = (); }
  260. sub enablecache { $cache = 1; }
  261. sub disablecache { $cache = 0; }
  262. # --- Functions to process the 'time' data type
  263. sub new { my @t = (time, times, @_ == 2 ? $_[1] : 0);
  264. print "new=@t\n" if $debug;
  265. bless \@t; }
  266. sub cpu_p { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $pu+$ps ; }
  267. sub cpu_c { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $cu+$cs ; }
  268. sub cpu_a { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $pu+$ps+$cu+$cs ; }
  269. sub real { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $r ; }
  270. sub iters { $_[0]->[5] ; }
  271. sub timediff {
  272. my($a, $b) = @_;
  273. my @r;
  274. for (my $i=0; $i < @$a; ++$i) {
  275. push(@r, $a->[$i] - $b->[$i]);
  276. }
  277. bless \@r;
  278. }
  279. sub timesum {
  280. my($a, $b) = @_;
  281. my @r;
  282. for (my $i=0; $i < @$a; ++$i) {
  283. push(@r, $a->[$i] + $b->[$i]);
  284. }
  285. bless \@r;
  286. }
  287. sub timestr {
  288. my($tr, $style, $f) = @_;
  289. my @t = @$tr;
  290. warn "bad time value (@t)" unless @t==6;
  291. my($r, $pu, $ps, $cu, $cs, $n) = @t;
  292. my($pt, $ct, $tt) = ($tr->cpu_p, $tr->cpu_c, $tr->cpu_a);
  293. $f = $defaultfmt unless defined $f;
  294. # format a time in the required style, other formats may be added here
  295. $style ||= $defaultstyle;
  296. $style = ($ct>0) ? 'all' : 'noc' if $style eq 'auto';
  297. my $s = "@t $style"; # default for unknown style
  298. $s=sprintf("%2d wallclock secs (%$f usr %$f sys + %$f cusr %$f csys = %$f CPU)",
  299. $r,$pu,$ps,$cu,$cs,$tt) if $style eq 'all';
  300. $s=sprintf("%2d wallclock secs (%$f usr + %$f sys = %$f CPU)",
  301. $r,$pu,$ps,$pt) if $style eq 'noc';
  302. $s=sprintf("%2d wallclock secs (%$f cusr + %$f csys = %$f CPU)",
  303. $r,$cu,$cs,$ct) if $style eq 'nop';
  304. $s .= sprintf(" @ %$f/s (n=$n)", $n / ( $pu + $ps )) if $n && $pu+$ps;
  305. $s;
  306. }
  307. sub timedebug {
  308. my($msg, $t) = @_;
  309. print STDERR "$msg",timestr($t),"\n" if $debug;
  310. }
  311. # --- Functions implementing low-level support for timing loops
  312. sub runloop {
  313. my($n, $c) = @_;
  314. $n+=0; # force numeric now, so garbage won't creep into the eval
  315. croak "negative loopcount $n" if $n<0;
  316. confess "Usage: runloop(number, [string | coderef])" unless defined $c;
  317. my($t0, $t1, $td); # before, after, difference
  318. # find package of caller so we can execute code there
  319. my($curpack) = caller(0);
  320. my($i, $pack)= 0;
  321. while (($pack) = caller(++$i)) {
  322. last if $pack ne $curpack;
  323. }
  324. my ($subcode, $subref);
  325. if (ref $c eq 'CODE') {
  326. $subcode = "sub { for (1 .. $n) { local \$_; package $pack; &\$c; } }";
  327. $subref = eval $subcode;
  328. }
  329. else {
  330. $subcode = "sub { for (1 .. $n) { local \$_; package $pack; $c;} }";
  331. $subref = _doeval($subcode);
  332. }
  333. croak "runloop unable to compile '$c': $@\ncode: $subcode\n" if $@;
  334. print STDERR "runloop $n '$subcode'\n" if $debug;
  335. # Wait for the user timer to tick. This makes the error range more like
  336. # -0.01, +0. If we don't wait, then it's more like -0.01, +0.01. This
  337. # may not seem important, but it significantly reduces the chances of
  338. # getting a too low initial $n in the initial, 'find the minimum' loop
  339. # in &countit. This, in turn, can reduce the number of calls to
  340. # &runloop a lot, and thus reduce additive errors.
  341. my $tbase = Benchmark->new(0)->[1];
  342. while ( ( $t0 = Benchmark->new(0) )->[1] == $tbase ) {} ;
  343. &$subref;
  344. $t1 = Benchmark->new($n);
  345. $td = &timediff($t1, $t0);
  346. timedebug("runloop:",$td);
  347. $td;
  348. }
  349. sub timeit {
  350. my($n, $code) = @_;
  351. my($wn, $wc, $wd);
  352. printf STDERR "timeit $n $code\n" if $debug;
  353. my $cache_key = $n . ( ref( $code ) ? 'c' : 's' );
  354. if ($cache && exists $cache{$cache_key} ) {
  355. $wn = $cache{$cache_key};
  356. } else {
  357. $wn = &runloop($n, ref( $code ) ? sub { undef } : '' );
  358. # Can't let our baseline have any iterations, or they get subtracted
  359. # out of the result.
  360. $wn->[5] = 0;
  361. $cache{$cache_key} = $wn;
  362. }
  363. $wc = &runloop($n, $code);
  364. $wd = timediff($wc, $wn);
  365. timedebug("timeit: ",$wc);
  366. timedebug(" - ",$wn);
  367. timedebug(" = ",$wd);
  368. $wd;
  369. }
  370. my $default_for = 3;
  371. my $min_for = 0.1;
  372. sub countit {
  373. my ( $tmax, $code ) = @_;
  374. if ( not defined $tmax or $tmax == 0 ) {
  375. $tmax = $default_for;
  376. } elsif ( $tmax < 0 ) {
  377. $tmax = -$tmax;
  378. }
  379. die "countit($tmax, ...): timelimit cannot be less than $min_for.\n"
  380. if $tmax < $min_for;
  381. my ($n, $tc);
  382. # First find the minimum $n that gives a significant timing.
  383. for ($n = 1; ; $n *= 2 ) {
  384. my $td = timeit($n, $code);
  385. $tc = $td->[1] + $td->[2];
  386. last if $tc > 0.1;
  387. }
  388. my $nmin = $n;
  389. # Get $n high enough that we can guess the final $n with some accuracy.
  390. my $tpra = 0.1 * $tmax; # Target/time practice.
  391. while ( $tc < $tpra ) {
  392. # The 5% fudge is to keep us from iterating again all
  393. # that often (this speeds overall responsiveness when $tmax is big
  394. # and we guess a little low). This does not noticably affect
  395. # accuracy since we're not couting these times.
  396. $n = int( $tpra * 1.05 * $n / $tc ); # Linear approximation.
  397. my $td = timeit($n, $code);
  398. my $new_tc = $td->[1] + $td->[2];
  399. # Make sure we are making progress.
  400. $tc = $new_tc > 1.2 * $tc ? $new_tc : 1.2 * $tc;
  401. }
  402. # Now, do the 'for real' timing(s), repeating until we exceed
  403. # the max.
  404. my $ntot = 0;
  405. my $rtot = 0;
  406. my $utot = 0.0;
  407. my $stot = 0.0;
  408. my $cutot = 0.0;
  409. my $cstot = 0.0;
  410. my $ttot = 0.0;
  411. # The 5% fudge is because $n is often a few % low even for routines
  412. # with stable times and avoiding extra timeit()s is nice for
  413. # accuracy's sake.
  414. $n = int( $n * ( 1.05 * $tmax / $tc ) );
  415. while () {
  416. my $td = timeit($n, $code);
  417. $ntot += $n;
  418. $rtot += $td->[0];
  419. $utot += $td->[1];
  420. $stot += $td->[2];
  421. $cutot += $td->[3];
  422. $cstot += $td->[4];
  423. $ttot = $utot + $stot;
  424. last if $ttot >= $tmax;
  425. $ttot = 0.01 if $ttot < 0.01;
  426. my $r = $tmax / $ttot - 1; # Linear approximation.
  427. $n = int( $r * $ntot );
  428. $n = $nmin if $n < $nmin;
  429. }
  430. return bless [ $rtot, $utot, $stot, $cutot, $cstot, $ntot ];
  431. }
  432. # --- Functions implementing high-level time-then-print utilities
  433. sub n_to_for {
  434. my $n = shift;
  435. return $n == 0 ? $default_for : $n < 0 ? -$n : undef;
  436. }
  437. sub timethis{
  438. my($n, $code, $title, $style) = @_;
  439. my($t, $for, $forn);
  440. if ( $n > 0 ) {
  441. croak "non-integer loopcount $n, stopped" if int($n)<$n;
  442. $t = timeit($n, $code);
  443. $title = "timethis $n" unless defined $title;
  444. } else {
  445. $fort = n_to_for( $n );
  446. $t = countit( $fort, $code );
  447. $title = "timethis for $fort" unless defined $title;
  448. $forn = $t->[-1];
  449. }
  450. local $| = 1;
  451. $style = "" unless defined $style;
  452. printf("%10s: ", $title) unless $style eq 'none';
  453. print timestr($t, $style, $defaultfmt),"\n" unless $style eq 'none';
  454. $n = $forn if defined $forn;
  455. # A conservative warning to spot very silly tests.
  456. # Don't assume that your benchmark is ok simply because
  457. # you don't get this warning!
  458. print " (warning: too few iterations for a reliable count)\n"
  459. if $n < $min_count
  460. || ($t->real < 1 && $n < 1000)
  461. || $t->cpu_a < $min_cpu;
  462. $t;
  463. }
  464. sub timethese{
  465. my($n, $alt, $style) = @_;
  466. die "usage: timethese(count, { 'Name1'=>'code1', ... }\n"
  467. unless ref $alt eq HASH;
  468. my @names = sort keys %$alt;
  469. $style = "" unless defined $style;
  470. print "Benchmark: " unless $style eq 'none';
  471. if ( $n > 0 ) {
  472. croak "non-integer loopcount $n, stopped" if int($n)<$n;
  473. print "timing $n iterations of" unless $style eq 'none';
  474. } else {
  475. print "running" unless $style eq 'none';
  476. }
  477. print " ", join(', ',@names) unless $style eq 'none';
  478. unless ( $n > 0 ) {
  479. my $for = n_to_for( $n );
  480. print ", each for at least $for CPU seconds" unless $style eq 'none';
  481. }
  482. print "...\n" unless $style eq 'none';
  483. # we could save the results in an array and produce a summary here
  484. # sum, min, max, avg etc etc
  485. my %results;
  486. foreach my $name (@names) {
  487. $results{$name} = timethis ($n, $alt -> {$name}, $name, $style);
  488. }
  489. return \%results;
  490. }
  491. sub cmpthese{
  492. my $results = ref $_[0] ? $_[0] : timethese( @_ );
  493. return $results
  494. if defined $_[2] && $_[2] eq 'none';
  495. # Flatten in to an array of arrays with the name as the first field
  496. my @vals = map{ [ $_, @{$results->{$_}} ] } keys %$results;
  497. for (@vals) {
  498. # The epsilon fudge here is to prevent div by 0. Since clock
  499. # resolutions are much larger, it's below the noise floor.
  500. my $rate = $_->[6] / ( $_->[2] + $_->[3] + 0.000000000000001 );
  501. $_->[7] = $rate;
  502. }
  503. # Sort by rate
  504. @vals = sort { $a->[7] <=> $b->[7] } @vals;
  505. # If more than half of the rates are greater than one...
  506. my $display_as_rate = $vals[$#vals>>1]->[7] > 1;
  507. my @rows;
  508. my @col_widths;
  509. my @top_row = (
  510. '',
  511. $display_as_rate ? 'Rate' : 's/iter',
  512. map { $_->[0] } @vals
  513. );
  514. push @rows, \@top_row;
  515. @col_widths = map { length( $_ ) } @top_row;
  516. # Build the data rows
  517. # We leave the last column in even though it never has any data. Perhaps
  518. # it should go away. Also, perhaps a style for a single column of
  519. # percentages might be nice.
  520. for my $row_val ( @vals ) {
  521. my @row;
  522. # Column 0 = test name
  523. push @row, $row_val->[0];
  524. $col_widths[0] = length( $row_val->[0] )
  525. if length( $row_val->[0] ) > $col_widths[0];
  526. # Column 1 = performance
  527. my $row_rate = $row_val->[7];
  528. # We assume that we'll never get a 0 rate.
  529. my $a = $display_as_rate ? $row_rate : 1 / $row_rate;
  530. # Only give a few decimal places before switching to sci. notation,
  531. # since the results aren't usually that accurate anyway.
  532. my $format =
  533. $a >= 100 ?
  534. "%0.0f" :
  535. $a >= 10 ?
  536. "%0.1f" :
  537. $a >= 1 ?
  538. "%0.2f" :
  539. $a >= 0.1 ?
  540. "%0.3f" :
  541. "%0.2e";
  542. $format .= "/s"
  543. if $display_as_rate;
  544. # Using $b here due to optimizing bug in _58 through _61
  545. my $b = sprintf( $format, $a );
  546. push @row, $b;
  547. $col_widths[1] = length( $b )
  548. if length( $b ) > $col_widths[1];
  549. # Columns 2..N = performance ratios
  550. my $skip_rest = 0;
  551. for ( my $col_num = 0 ; $col_num < @vals ; ++$col_num ) {
  552. my $col_val = $vals[$col_num];
  553. my $out;
  554. if ( $skip_rest ) {
  555. $out = '';
  556. }
  557. elsif ( $col_val->[0] eq $row_val->[0] ) {
  558. $out = "--";
  559. # $skip_rest = 1;
  560. }
  561. else {
  562. my $col_rate = $col_val->[7];
  563. $out = sprintf( "%.0f%%", 100*$row_rate/$col_rate - 100 );
  564. }
  565. push @row, $out;
  566. $col_widths[$col_num+2] = length( $out )
  567. if length( $out ) > $col_widths[$col_num+2];
  568. # A little wierdness to set the first column width properly
  569. $col_widths[$col_num+2] = length( $col_val->[0] )
  570. if length( $col_val->[0] ) > $col_widths[$col_num+2];
  571. }
  572. push @rows, \@row;
  573. }
  574. # Equalize column widths in the chart as much as possible without
  575. # exceeding 80 characters. This does not use or affect cols 0 or 1.
  576. my @sorted_width_refs =
  577. sort { $$a <=> $$b } map { \$_ } @col_widths[2..$#col_widths];
  578. my $max_width = ${$sorted_width_refs[-1]};
  579. my $total = @col_widths - 1 ;
  580. for ( @col_widths ) { $total += $_ }
  581. STRETCHER:
  582. while ( $total < 80 ) {
  583. my $min_width = ${$sorted_width_refs[0]};
  584. last
  585. if $min_width == $max_width;
  586. for ( @sorted_width_refs ) {
  587. last
  588. if $$_ > $min_width;
  589. ++$$_;
  590. ++$total;
  591. last STRETCHER
  592. if $total >= 80;
  593. }
  594. }
  595. # Dump the output
  596. my $format = join( ' ', map { "%${_}s" } @col_widths ) . "\n";
  597. substr( $format, 1, 0 ) = '-';
  598. for ( @rows ) {
  599. printf $format, @$_;
  600. }
  601. return $results;
  602. }
  603. 1;