Source code of Windows XP (NT5)
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.

529 lines
14 KiB

  1. package Benchmark;
  2. =head1 NAME
  3. Benchmark - benchmark running times of code
  4. timethis - run a chunk of code several times
  5. timethese - run several chunks of code several times
  6. timeit - run a chunk of code and see how long it goes
  7. =head1 SYNOPSIS
  8. timethis ($count, "code");
  9. # Use Perl code in strings...
  10. timethese($count, {
  11. 'Name1' => '...code1...',
  12. 'Name2' => '...code2...',
  13. });
  14. # ... or use subroutine references.
  15. timethese($count, {
  16. 'Name1' => sub { ...code1... },
  17. 'Name2' => sub { ...code2... },
  18. });
  19. $t = timeit($count, '...other code...')
  20. print "$count loops of other code took:",timestr($t),"\n";
  21. =head1 DESCRIPTION
  22. The Benchmark module encapsulates a number of routines to help you
  23. figure out how long it takes to execute some code.
  24. =head2 Methods
  25. =over 10
  26. =item new
  27. Returns the current time. Example:
  28. use Benchmark;
  29. $t0 = new Benchmark;
  30. # ... your code here ...
  31. $t1 = new Benchmark;
  32. $td = timediff($t1, $t0);
  33. print "the code took:",timestr($td),"\n";
  34. =item debug
  35. Enables or disable debugging by setting the C<$Benchmark::Debug> flag:
  36. debug Benchmark 1;
  37. $t = timeit(10, ' 5 ** $Global ');
  38. debug Benchmark 0;
  39. =back
  40. =head2 Standard Exports
  41. The following routines will be exported into your namespace
  42. if you use the Benchmark module:
  43. =over 10
  44. =item timeit(COUNT, CODE)
  45. Arguments: COUNT is the number of times to run the loop, and CODE is
  46. the code to run. CODE may be either a code reference or a string to
  47. be eval'd; either way it will be run in the caller's package.
  48. Returns: a Benchmark object.
  49. =item timethis ( COUNT, CODE, [ TITLE, [ STYLE ]] )
  50. Time COUNT iterations of CODE. CODE may be a string to eval or a
  51. code reference; either way the CODE will run in the caller's package.
  52. Results will be printed to STDOUT as TITLE followed by the times.
  53. TITLE defaults to "timethis COUNT" if none is provided. STYLE
  54. determines the format of the output, as described for timestr() below.
  55. The COUNT can be zero or negative: this means the I<minimum number of
  56. CPU seconds> to run. A zero signifies the default of 3 seconds. For
  57. example to run at least for 10 seconds:
  58. timethis(-10, $code)
  59. or to run two pieces of code tests for at least 3 seconds:
  60. timethese(0, { test1 => '...', test2 => '...'})
  61. CPU seconds is, in UNIX terms, the user time plus the system time of
  62. the process itself, as opposed to the real (wallclock) time and the
  63. time spent by the child processes. Less than 0.1 seconds is not
  64. accepted (-0.01 as the count, for example, will cause a fatal runtime
  65. exception).
  66. Note that the CPU seconds is the B<minimum> time: CPU scheduling and
  67. other operating system factors may complicate the attempt so that a
  68. little bit more time is spent. The benchmark output will, however,
  69. also tell the number of C<$code> runs/second, which should be a more
  70. interesting number than the actually spent seconds.
  71. Returns a Benchmark object.
  72. =item timethese ( COUNT, CODEHASHREF, [ STYLE ] )
  73. The CODEHASHREF is a reference to a hash containing names as keys
  74. and either a string to eval or a code reference for each value.
  75. For each (KEY, VALUE) pair in the CODEHASHREF, this routine will
  76. call
  77. timethis(COUNT, VALUE, KEY, STYLE)
  78. The routines are called in string comparison order of KEY.
  79. The COUNT can be zero or negative, see timethis().
  80. =item timediff ( T1, T2 )
  81. Returns the difference between two Benchmark times as a Benchmark
  82. object suitable for passing to timestr().
  83. =item timesum ( T1, T2 )
  84. Returns the sum of two Benchmark times as a Benchmark object suitable
  85. for passing to timestr().
  86. =item timestr ( TIMEDIFF, [ STYLE, [ FORMAT ] ] )
  87. Returns a string that formats the times in the TIMEDIFF object in
  88. the requested STYLE. TIMEDIFF is expected to be a Benchmark object
  89. similar to that returned by timediff().
  90. STYLE can be any of 'all', 'noc', 'nop' or 'auto'. 'all' shows each
  91. of the 5 times available ('wallclock' time, user time, system time,
  92. user time of children, and system time of children). 'noc' shows all
  93. except the two children times. 'nop' shows only wallclock and the
  94. two children times. 'auto' (the default) will act as 'all' unless
  95. the children times are both zero, in which case it acts as 'noc'.
  96. FORMAT is the L<printf(3)>-style format specifier (without the
  97. leading '%') to use to print the times. It defaults to '5.2f'.
  98. =back
  99. =head2 Optional Exports
  100. The following routines will be exported into your namespace
  101. if you specifically ask that they be imported:
  102. =over 10
  103. =item clearcache ( COUNT )
  104. Clear the cached time for COUNT rounds of the null loop.
  105. =item clearallcache ( )
  106. Clear all cached times.
  107. =item disablecache ( )
  108. Disable caching of timings for the null loop. This will force Benchmark
  109. to recalculate these timings for each new piece of code timed.
  110. =item enablecache ( )
  111. Enable caching of timings for the null loop. The time taken for COUNT
  112. rounds of the null loop will be calculated only once for each
  113. different COUNT used.
  114. =back
  115. =head1 NOTES
  116. The data is stored as a list of values from the time and times
  117. functions:
  118. ($real, $user, $system, $children_user, $children_system)
  119. in seconds for the whole loop (not divided by the number of rounds).
  120. The timing is done using time(3) and times(3).
  121. Code is executed in the caller's package.
  122. The time of the null loop (a loop with the same
  123. number of rounds but empty loop body) is subtracted
  124. from the time of the real loop.
  125. The null loop times are cached, the key being the
  126. number of rounds. The caching can be controlled using
  127. calls like these:
  128. clearcache($key);
  129. clearallcache();
  130. disablecache();
  131. enablecache();
  132. =head1 INHERITANCE
  133. Benchmark inherits from no other class, except of course
  134. for Exporter.
  135. =head1 CAVEATS
  136. Comparing eval'd strings with code references will give you
  137. inaccurate results: a code reference will show a slower
  138. execution time than the equivalent eval'd string.
  139. The real time timing is done using time(2) and
  140. the granularity is therefore only one second.
  141. Short tests may produce negative figures because perl
  142. can appear to take longer to execute the empty loop
  143. than a short test; try:
  144. timethis(100,'1');
  145. The system time of the null loop might be slightly
  146. more than the system time of the loop with the actual
  147. code and therefore the difference might end up being E<lt> 0.
  148. =head1 AUTHORS
  149. Jarkko Hietaniemi <F<[email protected]>>, Tim Bunce <F<[email protected]>>
  150. =head1 MODIFICATION HISTORY
  151. September 8th, 1994; by Tim Bunce.
  152. March 28th, 1997; by Hugo van der Sanden: added support for code
  153. references and the already documented 'debug' method; revamped
  154. documentation.
  155. April 04-07th, 1997: by Jarkko Hietaniemi, added the run-for-some-time
  156. functionality.
  157. =cut
  158. # evaluate something in a clean lexical environment
  159. sub _doeval { eval shift }
  160. #
  161. # put any lexicals at file scope AFTER here
  162. #
  163. use Carp;
  164. use Exporter;
  165. @ISA=(Exporter);
  166. @EXPORT=qw(timeit timethis timethese timediff timestr);
  167. @EXPORT_OK=qw(clearcache clearallcache disablecache enablecache);
  168. &init;
  169. sub init {
  170. $debug = 0;
  171. $min_count = 4;
  172. $min_cpu = 0.4;
  173. $defaultfmt = '5.2f';
  174. $defaultstyle = 'auto';
  175. # The cache can cause a slight loss of sys time accuracy. If a
  176. # user does many tests (>10) with *very* large counts (>10000)
  177. # or works on a very slow machine the cache may be useful.
  178. &disablecache;
  179. &clearallcache;
  180. }
  181. sub debug { $debug = ($_[1] != 0); }
  182. sub clearcache { delete $cache{$_[0]}; }
  183. sub clearallcache { %cache = (); }
  184. sub enablecache { $cache = 1; }
  185. sub disablecache { $cache = 0; }
  186. # --- Functions to process the 'time' data type
  187. sub new { my @t = (time, times, @_ == 2 ? $_[1] : 0);
  188. print "new=@t\n" if $debug;
  189. bless \@t; }
  190. sub cpu_p { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $pu+$ps ; }
  191. sub cpu_c { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $cu+$cs ; }
  192. sub cpu_a { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $pu+$ps+$cu+$cs ; }
  193. sub real { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $r ; }
  194. sub timediff {
  195. my($a, $b) = @_;
  196. my @r;
  197. for (my $i=0; $i < @$a; ++$i) {
  198. push(@r, $a->[$i] - $b->[$i]);
  199. }
  200. bless \@r;
  201. }
  202. sub timesum {
  203. my($a, $b) = @_;
  204. my @r;
  205. for (my $i=0; $i < @$a; ++$i) {
  206. push(@r, $a->[$i] + $b->[$i]);
  207. }
  208. bless \@r;
  209. }
  210. sub timestr {
  211. my($tr, $style, $f) = @_;
  212. my @t = @$tr;
  213. warn "bad time value (@t)" unless @t==6;
  214. my($r, $pu, $ps, $cu, $cs, $n) = @t;
  215. my($pt, $ct, $t) = ($tr->cpu_p, $tr->cpu_c, $tr->cpu_a);
  216. $f = $defaultfmt unless defined $f;
  217. # format a time in the required style, other formats may be added here
  218. $style ||= $defaultstyle;
  219. $style = ($ct>0) ? 'all' : 'noc' if $style eq 'auto';
  220. my $s = "@t $style"; # default for unknown style
  221. $s=sprintf("%2d wallclock secs (%$f usr %$f sys + %$f cusr %$f csys = %$f CPU)",
  222. @t,$t) if $style eq 'all';
  223. $s=sprintf("%2d wallclock secs (%$f usr + %$f sys = %$f CPU)",
  224. $r,$pu,$ps,$pt) if $style eq 'noc';
  225. $s=sprintf("%2d wallclock secs (%$f cusr + %$f csys = %$f CPU)",
  226. $r,$cu,$cs,$ct) if $style eq 'nop';
  227. $s .= sprintf(" @ %$f/s (n=$n)", $n / ( $pu + $ps )) if $n;
  228. $s;
  229. }
  230. sub timedebug {
  231. my($msg, $t) = @_;
  232. print STDERR "$msg",timestr($t),"\n" if $debug;
  233. }
  234. # --- Functions implementing low-level support for timing loops
  235. sub runloop {
  236. my($n, $c) = @_;
  237. $n+=0; # force numeric now, so garbage won't creep into the eval
  238. croak "negative loopcount $n" if $n<0;
  239. confess "Usage: runloop(number, [string | coderef])" unless defined $c;
  240. my($t0, $t1, $td); # before, after, difference
  241. # find package of caller so we can execute code there
  242. my($curpack) = caller(0);
  243. my($i, $pack)= 0;
  244. while (($pack) = caller(++$i)) {
  245. last if $pack ne $curpack;
  246. }
  247. my ($subcode, $subref);
  248. if (ref $c eq 'CODE') {
  249. $subcode = "sub { for (1 .. $n) { local \$_; package $pack; &\$c; } }";
  250. $subref = eval $subcode;
  251. }
  252. else {
  253. $subcode = "sub { for (1 .. $n) { local \$_; package $pack; $c;} }";
  254. $subref = _doeval($subcode);
  255. }
  256. croak "runloop unable to compile '$c': $@\ncode: $subcode\n" if $@;
  257. print STDERR "runloop $n '$subcode'\n" if $debug;
  258. $t0 = Benchmark->new(0);
  259. &$subref;
  260. $t1 = Benchmark->new($n);
  261. $td = &timediff($t1, $t0);
  262. timedebug("runloop:",$td);
  263. $td;
  264. }
  265. sub timeit {
  266. my($n, $code) = @_;
  267. my($wn, $wc, $wd);
  268. printf STDERR "timeit $n $code\n" if $debug;
  269. if ($cache && exists $cache{$n}) {
  270. $wn = $cache{$n};
  271. } else {
  272. $wn = &runloop($n, '');
  273. $cache{$n} = $wn;
  274. }
  275. $wc = &runloop($n, $code);
  276. $wd = timediff($wc, $wn);
  277. timedebug("timeit: ",$wc);
  278. timedebug(" - ",$wn);
  279. timedebug(" = ",$wd);
  280. $wd;
  281. }
  282. my $default_for = 3;
  283. my $min_for = 0.1;
  284. sub runfor {
  285. my ($code, $tmax) = @_;
  286. if ( not defined $tmax or $tmax == 0 ) {
  287. $tmax = $default_for;
  288. } elsif ( $tmax < 0 ) {
  289. $tmax = -$tmax;
  290. }
  291. die "runfor(..., $tmax): timelimit cannot be less than $min_for.\n"
  292. if $tmax < $min_for;
  293. my ($n, $td, $tc, $ntot, $rtot, $utot, $stot, $cutot, $cstot );
  294. # First find the minimum $n that gives a non-zero timing.
  295. my $nmin;
  296. for ($n = 1, $tc = 0; $tc <= 0; $n *= 2 ) {
  297. $td = timeit($n, $code);
  298. $tc = $td->[1] + $td->[2];
  299. }
  300. $nmin = $n;
  301. my $ttot = 0;
  302. my $tpra = 0.05 * $tmax; # Target/time practice.
  303. # Double $n until we have think we have practiced enough.
  304. for ( $n = 1; $ttot < $tpra; $n *= 2 ) {
  305. $td = timeit($n, $code);
  306. $tc = $td->cpu_p;
  307. $ntot += $n;
  308. $rtot += $td->[0];
  309. $utot += $td->[1];
  310. $stot += $td->[2];
  311. $ttot = $utot + $stot;
  312. $cutot += $td->[3];
  313. $cstot += $td->[4];
  314. }
  315. my $r;
  316. # Then iterate towards the $tmax.
  317. while ( $ttot < $tmax ) {
  318. $r = $tmax / $ttot - 1; # Linear approximation.
  319. $n = int( $r * $n );
  320. $n = $nmin if $n < $nmin;
  321. $td = timeit($n, $code);
  322. $ntot += $n;
  323. $rtot += $td->[0];
  324. $utot += $td->[1];
  325. $stot += $td->[2];
  326. $ttot = $utot + $stot;
  327. $cutot += $td->[3];
  328. $cstot += $td->[4];
  329. }
  330. return bless [ $rtot, $utot, $stot, $cutot, $cstot, $ntot ];
  331. }
  332. # --- Functions implementing high-level time-then-print utilities
  333. sub n_to_for {
  334. my $n = shift;
  335. return $n == 0 ? $default_for : $n < 0 ? -$n : undef;
  336. }
  337. sub timethis{
  338. my($n, $code, $title, $style) = @_;
  339. my($t, $for, $forn);
  340. if ( $n > 0 ) {
  341. croak "non-integer loopcount $n, stopped" if int($n)<$n;
  342. $t = timeit($n, $code);
  343. $title = "timethis $n" unless defined $title;
  344. } else {
  345. $fort = n_to_for( $n );
  346. $t = runfor($code, $fort);
  347. $title = "timethis for $fort" unless defined $title;
  348. $forn = $t->[-1];
  349. }
  350. local $| = 1;
  351. $style = "" unless defined $style;
  352. printf("%10s: ", $title);
  353. print timestr($t, $style, $defaultfmt),"\n";
  354. $n = $forn if defined $forn;
  355. # A conservative warning to spot very silly tests.
  356. # Don't assume that your benchmark is ok simply because
  357. # you don't get this warning!
  358. print " (warning: too few iterations for a reliable count)\n"
  359. if $n < $min_count
  360. || ($t->real < 1 && $n < 1000)
  361. || $t->cpu_a < $min_cpu;
  362. $t;
  363. }
  364. sub timethese{
  365. my($n, $alt, $style) = @_;
  366. die "usage: timethese(count, { 'Name1'=>'code1', ... }\n"
  367. unless ref $alt eq HASH;
  368. my @names = sort keys %$alt;
  369. $style = "" unless defined $style;
  370. print "Benchmark: ";
  371. if ( $n > 0 ) {
  372. croak "non-integer loopcount $n, stopped" if int($n)<$n;
  373. print "timing $n iterations of";
  374. } else {
  375. print "running";
  376. }
  377. print " ", join(', ',@names);
  378. unless ( $n > 0 ) {
  379. my $for = n_to_for( $n );
  380. print ", each for at least $for CPU seconds";
  381. }
  382. print "...\n";
  383. # we could save the results in an array and produce a summary here
  384. # sum, min, max, avg etc etc
  385. foreach my $name (@names) {
  386. timethis ($n, $alt -> {$name}, $name, $style);
  387. }
  388. }
  389. 1;