home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / perl501m.zip / lib / Benchmark.pm < prev    next >
Text File  |  1995-07-03  |  10KB  |  412 lines

  1. package Benchmark;
  2.  
  3. =head1 NAME
  4.  
  5. Benchmark - benchmark running times of code
  6.  
  7. timethis - run a chunk of code several times
  8.  
  9. timethese - run several chunks of code several times
  10.  
  11. timeit - run a chunk of code and see how long it goes
  12.  
  13. =head1 SYNOPSIS
  14.  
  15.     timethis ($count, "code");
  16.  
  17.     timethese($count, {
  18.     'Name1' => '...code1...',
  19.     'Name2' => '...code2...',
  20.     });
  21.  
  22.     $t = timeit($count, '...other code...')
  23.     print "$count loops of other code took:",timestr($t),"\n";
  24.  
  25. =head1 DESCRIPTION
  26.  
  27. The Benchmark module encapsulates a number of routines to help you
  28. figure out how long it takes to execute some code.
  29.  
  30. =head2 Methods
  31.  
  32. =over 10
  33.  
  34. =item new
  35.  
  36. Returns the current time.   Example:
  37.  
  38.     use Benchmark;
  39.     $t0 = new Benchmark;
  40.     # ... your code here ...
  41.     $t1 = new Benchmark;
  42.     $td = timediff($t1, $t0);
  43.     print "the code took:",timestr($dt),"\n";
  44.  
  45. =item debug
  46.  
  47. Enables or disable debugging by setting the C<$Benchmark::Debug> flag:
  48.  
  49.     debug Benchmark 1; 
  50.     $t = timeit(10, ' 5 ** $Global ');
  51.     debug Benchmark 0; 
  52.  
  53. =back
  54.  
  55. =head2 Standard Exports
  56.  
  57. The following routines will be exported into your namespace 
  58. if you use the Benchmark module:
  59.  
  60. =over 10
  61.  
  62. =item timeit(COUNT, CODE)
  63.  
  64. Arguments: COUNT is the number of time to run the loop, and 
  65. the second is the code to run.  CODE may be a string containing the code,
  66. a reference to the function to run, or a reference to a hash containing 
  67. keys which are names and values which are more CODE specs.
  68.  
  69. Side-effects: prints out noise to standard out.
  70.  
  71. Returns: a Benchmark object.  
  72.  
  73. =item timethis
  74.  
  75. =item timethese
  76.  
  77. =item timediff
  78.  
  79. =item timestr
  80.  
  81. =back
  82.  
  83. =head2 Optional Exports
  84.  
  85. The following routines will be exported into your namespace
  86. if you specifically ask that they be imported:
  87.  
  88. =over 10
  89.  
  90. clearcache
  91.  
  92. clearallcache
  93.  
  94. disablecache
  95.  
  96. enablecache
  97.  
  98. =back
  99.  
  100. =head1 NOTES
  101.  
  102. The data is stored as a list of values from the time and times
  103. functions: 
  104.  
  105.       ($real, $user, $system, $children_user, $children_system)
  106.  
  107. in seconds for the whole loop (not divided by the number of rounds).
  108.  
  109. The timing is done using time(3) and times(3).
  110.  
  111. Code is executed in the caller's package.
  112.  
  113. Enable debugging by:  
  114.  
  115.     $Benchmark::debug = 1;
  116.  
  117. The time of the null loop (a loop with the same
  118. number of rounds but empty loop body) is subtracted
  119. from the time of the real loop.
  120.  
  121. The null loop times are cached, the key being the
  122. number of rounds. The caching can be controlled using
  123. calls like these:
  124.  
  125.     clearcache($key); 
  126.     clearallcache();
  127.  
  128.     disablecache(); 
  129.     enablecache();
  130.  
  131. =head1 INHERITANCE
  132.  
  133. Benchmark inherits from no other class, except of course
  134. for Exporter.
  135.  
  136. =head1 CAVEATS
  137.  
  138. The real time timing is done using time(2) and
  139. the granularity is therefore only one second.
  140.  
  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.  
  145.     timethis(100,'1');
  146.  
  147. The system time of the null loop might be slightly
  148. more than the system time of the loop with the actual
  149. code and therefore the difference might end up being < 0.
  150.  
  151. More documentation is needed :-( especially for styles and formats.
  152.  
  153. =head1 AUTHORS
  154.  
  155. Jarkko Hietaniemi <Jarkko.Hietaniemi@hut.fi>,
  156. Tim Bunce <Tim.Bunce@ig.co.uk>
  157.  
  158. =head1 MODIFICATION HISTORY
  159.  
  160. September 8th, 1994; by Tim Bunce.
  161.  
  162. =cut
  163.  
  164. # Purpose: benchmark running times of code.
  165. #
  166. #
  167. # Usage - to time code snippets and print results:
  168. #
  169. #    timethis($count, '...code...');
  170. #        
  171. # prints:
  172. #    timethis 100:  2 secs ( 0.23 usr  0.10 sys =  0.33 cpu)
  173. #
  174. #
  175. #    timethese($count, {
  176. #        Name1 => '...code1...',
  177. #        Name2 => '...code2...',
  178. #        ... });
  179. # prints:
  180. #    Benchmark: timing 100 iterations of Name1, Name2...
  181. #         Name1:  2 secs ( 0.50 usr  0.00 sys =  0.50 cpu)
  182. #         Name2:  1 secs ( 0.48 usr  0.00 sys =  0.48 cpu)
  183. #
  184. # The default display style will automatically add child process
  185. # values if non-zero.
  186. #
  187. #
  188. # Usage - to time sections of your own code:
  189. #
  190. #    use Benchmark;
  191. #    $t0 = new Benchmark;
  192. #    ... your code here ...
  193. #    $t1 = new Benchmark;
  194. #    $td = &timediff($t1, $t0);
  195. #    print "the code took:",timestr($td),"\n";
  196. #
  197. #    $t = &timeit($count, '...other code...')
  198. #    print "$count loops of other code took:",timestr($t),"\n";
  199. #
  200. # Data format:
  201. #       The data is stored as a list of values from the time and times
  202. #       functions: ($real, $user, $system, $children_user, $children_system)
  203. #    in seconds for the whole loop (not divided by the number of rounds).
  204. #        
  205. # Internals:
  206. #    The timing is done using time(3) and times(3).
  207. #        
  208. #    Code is executed in the callers package
  209. #
  210. #    Enable debugging by:  $Benchmark::debug = 1;
  211. #
  212. #    The time of the null loop (a loop with the same
  213. #    number of rounds but empty loop body) is substracted
  214. #    from the time of the real loop.
  215. #
  216. #    The null loop times are cached, the key being the
  217. #    number of rounds. The caching can be controlled using
  218. #    &clearcache($key); &clearallcache;
  219. #    &disablecache; &enablecache;
  220. #
  221. # Caveats:
  222. #
  223. #    The real time timing is done using time(2) and
  224. #    the granularity is therefore only one second.
  225. #
  226. #    Short tests may produce negative figures because perl
  227. #    can appear to take longer to execute the empty loop 
  228. #    than a short test: try timethis(100,'1');
  229. #
  230. #    The system time of the null loop might be slightly
  231. #    more than the system time of the loop with the actual
  232. #    code and therefore the difference might end up being < 0
  233. #
  234. #    More documentation is needed :-(
  235. #    Especially for styles and formats.
  236. #
  237. # Authors:    Jarkko Hietaniemi <Jarkko.Hietaniemi@hut.fi>
  238. #         Tim Bunce <Tim.Bunce@ig.co.uk>
  239. #
  240. #
  241. # Last updated:    Sept 8th 94 by Tim Bunce
  242. #
  243.  
  244. use Carp;
  245. use Exporter;
  246. @ISA=(Exporter);
  247. @EXPORT=qw(timeit timethis timethese timediff timestr);
  248. @EXPORT_OK=qw(clearcache clearallcache disablecache enablecache);
  249.  
  250. &init;
  251.  
  252. sub init {
  253.     $debug = 0;
  254.     $min_count = 4;
  255.     $min_cpu   = 0.4;
  256.     $defaultfmt = '5.2f';
  257.     $defaultstyle = 'auto';
  258.     # The cache can cause a slight loss of sys time accuracy. If a
  259.     # user does many tests (>10) with *very* large counts (>10000)
  260.     # or works on a very slow machine the cache may be useful.
  261.     &disablecache;
  262.     &clearallcache;
  263. }
  264.  
  265. sub clearcache    { delete $cache{$_[0]}; }
  266. sub clearallcache { %cache = (); }
  267. sub enablecache   { $cache = 1; }
  268. sub disablecache  { $cache = 0; }
  269.  
  270.  
  271. # --- Functions to process the 'time' data type
  272.  
  273. sub new { my(@t)=(time, times); print "new=@t\n" if $debug; bless \@t; }
  274.  
  275. sub cpu_p { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $pu+$ps         ; }
  276. sub cpu_c { my($r,$pu,$ps,$cu,$cs) = @{$_[0]};         $cu+$cs ; }
  277. sub cpu_a { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $pu+$ps+$cu+$cs ; }
  278. sub real  { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $r              ; }
  279.  
  280. sub timediff{
  281.     my($a, $b) = @_;
  282.     my(@r);
  283.     for($i=0; $i < @$a; ++$i){
  284.     push(@r, $a->[$i] - $b->[$i]);
  285.     }
  286.     bless \@r;
  287. }
  288.  
  289. sub timestr{
  290.     my($tr, $style, $f) = @_;
  291.     my(@t) = @$tr;
  292.     warn "bad time value" unless @t==5;
  293.     my($r, $pu, $ps, $cu, $cs) = @t;
  294.     my($pt, $ct, $t) = ($tr->cpu_p, $tr->cpu_c, $tr->cpu_a);
  295.     $f = $defaultfmt unless $f;
  296.     # format a time in the required style, other formats may be added here
  297.     $style = $defaultstyle unless $style;
  298.     $style = ($ct>0) ? 'all' : 'noc' if $style=~/^auto$/;
  299.     my($s) = "@t $style"; # default for unknown style
  300.     $s=sprintf("%2d secs (%$f usr %$f sys + %$f cusr %$f csys = %$f cpu)",
  301.                 @t,$t) if $style =~ /^all$/;
  302.     $s=sprintf("%2d secs (%$f usr %$f sys = %$f cpu)",
  303.                 $r,$pu,$ps,$pt) if $style =~ /^noc$/;
  304.     $s=sprintf("%2d secs (%$f cusr %$f csys = %$f cpu)",
  305.                 $r,$cu,$cs,$ct) if $style =~ /^nop$/;
  306.     $s;
  307. }
  308. sub timedebug{
  309.     my($msg, $t) = @_;
  310.     print STDERR "$msg",timestr($t),"\n" if ($debug);
  311. }
  312.  
  313.  
  314. # --- Functions implementing low-level support for timing loops
  315.  
  316. sub runloop {
  317.     my($n, $c) = @_;
  318.  
  319.     $n+=0; # force numeric now, so garbage won't creep into the eval
  320.     croak "negativ loopcount $n" if $n<0;
  321.     confess "Usage: runloop(number, string)" unless defined $c;
  322.     my($t0, $t1, $td); # before, after, difference
  323.  
  324.     # find package of caller so we can execute code there
  325.     my ($curpack) = caller(0);
  326.     my ($i, $pack)= 0;
  327.     while (($pack) = caller(++$i)) {
  328.     last if $pack ne $curpack;
  329.     }
  330.  
  331.     my $subcode = "sub { package $pack; my(\$_i)=$n; while (\$_i--){$c;} }";
  332.     my $subref  = eval $subcode;
  333.     croak "runloop unable to compile '$c': $@\ncode: $subcode\n" if $@;
  334.     print STDERR "runloop $n '$subcode'\n" if ($debug);
  335.  
  336.     $t0 = &new;
  337.     &$subref;
  338.     $t1 = &new;
  339.     $td = &timediff($t1, $t0);
  340.  
  341.     timedebug("runloop:",$td);
  342.     $td;
  343. }
  344.  
  345.  
  346. sub timeit {
  347.     my($n, $code) = @_;
  348.     my($wn, $wc, $wd);
  349.  
  350.     printf STDERR "timeit $n $code\n" if $debug;
  351.  
  352.     if ($cache && exists $cache{$n}){
  353.     $wn = $cache{$n};
  354.     }else{
  355.     $wn = &runloop($n, '');
  356.     $cache{$n} = $wn;
  357.     }
  358.  
  359.     $wc = &runloop($n, $code);
  360.  
  361.     $wd = timediff($wc, $wn);
  362.  
  363.     timedebug("timeit: ",$wc);
  364.     timedebug("      - ",$wn);
  365.     timedebug("      = ",$wd);
  366.  
  367.     $wd;
  368. }
  369.  
  370.  
  371. # --- Functions implementing high-level time-then-print utilities
  372.  
  373. sub timethis{
  374.     my($n, $code, $title, $style) = @_;
  375.     my($t) = timeit($n, $code);
  376.     local($|) = 1;
  377.     $title = "timethis $n" unless $title;
  378.     $style = "" unless $style;
  379.     printf("%10s: ", $title);
  380.     print timestr($t, $style),"\n";
  381.     # A conservative warning to spot very silly tests.
  382.     # Don't assume that your benchmark is ok simply because
  383.     # you don't get this warning!
  384.     print "            (warning: too few iterations for a reliable count)\n"
  385.     if (   $n < $min_count
  386.         || ($t->real < 1 && $n < 1000)
  387.         || $t->cpu_a < $min_cpu);
  388.     $t;
  389. }
  390.  
  391.  
  392. sub timethese{
  393.     my($n, $alt, $style) = @_;
  394.     die "usage: timethese(count, { 'Name1'=>'code1', ... }\n"
  395.         unless ref $alt eq HASH;
  396.     my(@all);
  397.     my(@names) = sort keys %$alt;
  398.     $style = "" unless $style;
  399.     print "Benchmark: timing $n iterations of ",join(', ',@names),"...\n";
  400.     foreach(@names){
  401.     $t = timethis($n, $alt->{$_}, $_, $style);
  402.     push(@all, $t);
  403.     }
  404.     # we could produce a summary from @all here
  405.     # sum, min, max, avg etc etc
  406.     @all;
  407. }
  408.  
  409.  
  410. 1;
  411.