1Benchmark(3pm)         Perl Programmers Reference Guide         Benchmark(3pm)
2
3
4

NAME

6       Benchmark - benchmark running times of Perl code
7

SYNOPSIS

9           use Benchmark qw(:all) ;
10
11           timethis ($count, "code");
12
13           # Use Perl code in strings...
14           timethese($count, {
15               'Name1' => '...code1...',
16               'Name2' => '...code2...',
17           });
18
19           # ... or use subroutine references.
20           timethese($count, {
21               'Name1' => sub { ...code1... },
22               'Name2' => sub { ...code2... },
23           });
24
25           # cmpthese can be used both ways as well
26           cmpthese($count, {
27               'Name1' => '...code1...',
28               'Name2' => '...code2...',
29           });
30
31           cmpthese($count, {
32               'Name1' => sub { ...code1... },
33               'Name2' => sub { ...code2... },
34           });
35
36           # ...or in two stages
37           $results = timethese($count,
38               {
39                   'Name1' => sub { ...code1... },
40                   'Name2' => sub { ...code2... },
41               },
42               'none'
43           );
44           cmpthese( $results ) ;
45
46           $t = timeit($count, '...other code...')
47           print "$count loops of other code took:",timestr($t),"\n";
48
49           $t = countit($time, '...other code...')
50           $count = $t->iters ;
51           print "$count loops of other code took:",timestr($t),"\n";
52
53           # enable hires wallclock timing if possible
54           use Benchmark ':hireswallclock';
55

DESCRIPTION

57       The Benchmark module encapsulates a number of routines to help you fig‐
58       ure out how long it takes to execute some code.
59
60       timethis - run a chunk of code several times
61
62       timethese - run several chunks of code several times
63
64       cmpthese - print results of timethese as a comparison chart
65
66       timeit - run a chunk of code and see how long it goes
67
68       countit - see how many times a chunk of code runs in a given time
69
70       Methods
71
72       new       Returns the current time.   Example:
73
74                     use Benchmark;
75                     $t0 = new Benchmark;
76                     # ... your code here ...
77                     $t1 = new Benchmark;
78                     $td = timediff($t1, $t0);
79                     print "the code took:",timestr($td),"\n";
80
81       debug     Enables or disable debugging by setting the $Benchmark::Debug
82                 flag:
83
84                     debug Benchmark 1;
85                     $t = timeit(10, ' 5 ** $Global ');
86                     debug Benchmark 0;
87
88       iters     Returns the number of iterations.
89
90       Standard Exports
91
92       The following routines will be exported into your namespace if you use
93       the Benchmark module:
94
95       timeit(COUNT, CODE)
96                 Arguments: COUNT is the number of times to run the loop, and
97                 CODE is the code to run.  CODE may be either a code reference
98                 or a string to be eval'd; either way it will be run in the
99                 caller's package.
100
101                 Returns: a Benchmark object.
102
103       timethis ( COUNT, CODE, [ TITLE, [ STYLE ]] )
104                 Time COUNT iterations of CODE. CODE may be a string to eval
105                 or a code reference; either way the CODE will run in the
106                 caller's package.  Results will be printed to STDOUT as TITLE
107                 followed by the times.  TITLE defaults to "timethis COUNT" if
108                 none is provided. STYLE determines the format of the output,
109                 as described for timestr() below.
110
111                 The COUNT can be zero or negative: this means the minimum
112                 number of CPU seconds to run.  A zero signifies the default
113                 of 3 seconds.  For example to run at least for 10 seconds:
114
115                         timethis(-10, $code)
116
117                 or to run two pieces of code tests for at least 3 seconds:
118
119                         timethese(0, { test1 => '...', test2 => '...'})
120
121                 CPU seconds is, in UNIX terms, the user time plus the system
122                 time of the process itself, as opposed to the real (wall‐
123                 clock) time and the time spent by the child processes.  Less
124                 than 0.1 seconds is not accepted (-0.01 as the count, for
125                 example, will cause a fatal runtime exception).
126
127                 Note that the CPU seconds is the minimum time: CPU scheduling
128                 and other operating system factors may complicate the attempt
129                 so that a little bit more time is spent.  The benchmark out‐
130                 put will, however, also tell the number of $code runs/second,
131                 which should be a more interesting number than the actually
132                 spent seconds.
133
134                 Returns a Benchmark object.
135
136       timethese ( COUNT, CODEHASHREF, [ STYLE ] )
137                 The CODEHASHREF is a reference to a hash containing names as
138                 keys and either a string to eval or a code reference for each
139                 value.  For each (KEY, VALUE) pair in the CODEHASHREF, this
140                 routine will call
141
142                         timethis(COUNT, VALUE, KEY, STYLE)
143
144                 The routines are called in string comparison order of KEY.
145
146                 The COUNT can be zero or negative, see timethis().
147
148                 Returns a hash of Benchmark objects, keyed by name.
149
150       timediff ( T1, T2 )
151                 Returns the difference between two Benchmark times as a
152                 Benchmark object suitable for passing to timestr().
153
154       timestr ( TIMEDIFF, [ STYLE, [ FORMAT ] ] )
155                 Returns a string that formats the times in the TIMEDIFF
156                 object in the requested STYLE. TIMEDIFF is expected to be a
157                 Benchmark object similar to that returned by timediff().
158
159                 STYLE can be any of 'all', 'none', 'noc', 'nop' or 'auto'.
160                 'all' shows each of the 5 times available ('wallclock' time,
161                 user time, system time, user time of children, and system
162                 time of children). 'noc' shows all except the two children
163                 times. 'nop' shows only wallclock and the two children times.
164                 'auto' (the default) will act as 'all' unless the children
165                 times are both zero, in which case it acts as 'noc'.  'none'
166                 prevents output.
167
168                 FORMAT is the printf(3)-style format specifier (without the
169                 leading '%') to use to print the times. It defaults to
170                 '5.2f'.
171
172       Optional Exports
173
174       The following routines will be exported into your namespace if you
175       specifically ask that they be imported:
176
177       clearcache ( COUNT )
178                 Clear the cached time for COUNT rounds of the null loop.
179
180       clearallcache ( )
181                 Clear all cached times.
182
183       cmpthese ( COUNT, CODEHASHREF, [ STYLE ] )
184       cmpthese ( RESULTSHASHREF, [ STYLE ] )
185                 Optionally calls timethese(), then outputs comparison chart.
186                 This:
187
188                     cmpthese( -1, { a => "++\$i", b => "\$i *= 2" } ) ;
189
190                 outputs a chart like:
191
192                            Rate    b    a
193                     b 2831802/s   -- -61%
194                     a 7208959/s 155%   --
195
196                 This chart is sorted from slowest to fastest, and shows the
197                 percent speed difference between each pair of tests.
198
199                 c<cmpthese> can also be passed the data structure that
200                 timethese() returns:
201
202                     $results = timethese( -1, { a => "++\$i", b => "\$i *= 2" } ) ;
203                     cmpthese( $results );
204
205                 in case you want to see both sets of results.
206
207                 Returns a reference to an ARRAY of rows, each row is an ARRAY
208                 of cells from the above chart, including labels. This:
209
210                     my $rows = cmpthese( -1, { a => '++$i', b => '$i *= 2' }, "none" );
211
212                 returns a data structure like:
213
214                     [
215                         [ '',       'Rate',   'b',    'a' ],
216                         [ 'b', '2885232/s',  '--', '-59%' ],
217                         [ 'a', '7099126/s', '146%',  '--' ],
218                     ]
219
220                 NOTE: This result value differs from previous versions, which
221                 returned the "timethese()" result structure.  If you want
222                 that, just use the two statement "timethese"..."cmpthese"
223                 idiom shown above.
224
225                 Incidently, note the variance in the result values between
226                 the two examples; this is typical of benchmarking.  If this
227                 were a real benchmark, you would probably want to run a lot
228                 more iterations.
229
230       countit(TIME, CODE)
231                 Arguments: TIME is the minimum length of time to run CODE
232                 for, and CODE is the code to run.  CODE may be either a code
233                 reference or a string to be eval'd; either way it will be run
234                 in the caller's package.
235
236                 TIME is not negative.  countit() will run the loop many times
237                 to calculate the speed of CODE before running it for TIME.
238                 The actual time run for will usually be greater than TIME due
239                 to system clock resolution, so it's best to look at the num‐
240                 ber of iterations divided by the times that you are concerned
241                 with, not just the iterations.
242
243                 Returns: a Benchmark object.
244
245       disablecache ( )
246                 Disable caching of timings for the null loop. This will force
247                 Benchmark to recalculate these timings for each new piece of
248                 code timed.
249
250       enablecache ( )
251                 Enable caching of timings for the null loop. The time taken
252                 for COUNT rounds of the null loop will be calculated only
253                 once for each different COUNT used.
254
255       timesum ( T1, T2 )
256                 Returns the sum of two Benchmark times as a Benchmark object
257                 suitable for passing to timestr().
258
259       :hireswallclock
260
261       If the Time::HiRes module has been installed, you can specify the spe‐
262       cial tag ":hireswallclock" for Benchmark (if Time::HiRes is not avail‐
263       able, the tag will be silently ignored).  This tag will cause the wall‐
264       clock time to be measured in microseconds, instead of integer seconds.
265       Note though that the speed computations are still conducted in CPU
266       time, not wallclock time.
267

NOTES

269       The data is stored as a list of values from the time and times func‐
270       tions:
271
272             ($real, $user, $system, $children_user, $children_system, $iters)
273
274       in seconds for the whole loop (not divided by the number of rounds).
275
276       The timing is done using time(3) and times(3).
277
278       Code is executed in the caller's package.
279
280       The time of the null loop (a loop with the same number of rounds but
281       empty loop body) is subtracted from the time of the real loop.
282
283       The null loop times can be cached, the key being the number of rounds.
284       The caching can be controlled using calls like these:
285
286           clearcache($key);
287           clearallcache();
288
289           disablecache();
290           enablecache();
291
292       Caching is off by default, as it can (usually slightly) decrease accu‐
293       racy and does not usually noticably affect runtimes.
294

EXAMPLES

296       For example,
297
298           use Benchmark qw( cmpthese ) ;
299           $x = 3;
300           cmpthese( -5, {
301               a => sub{$x*$x},
302               b => sub{$x**2},
303           } );
304
305       outputs something like this:
306
307          Benchmark: running a, b, each for at least 5 CPU seconds...
308                 Rate    b    a
309          b 1559428/s   -- -62%
310          a 4152037/s 166%   --
311
312       while
313
314           use Benchmark qw( timethese cmpthese ) ;
315           $x = 3;
316           $r = timethese( -5, {
317               a => sub{$x*$x},
318               b => sub{$x**2},
319           } );
320           cmpthese $r;
321
322       outputs something like this:
323
324           Benchmark: running a, b, each for at least 5 CPU seconds...
325                    a: 10 wallclock secs ( 5.14 usr +  0.13 sys =  5.27 CPU) @ 3835055.60/s (n=20210743)
326                    b:  5 wallclock secs ( 5.41 usr +  0.00 sys =  5.41 CPU) @ 1574944.92/s (n=8520452)
327                  Rate    b    a
328           b 1574945/s   -- -59%
329           a 3835056/s 144%   --
330

INHERITANCE

332       Benchmark inherits from no other class, except of course for Exporter.
333

CAVEATS

335       Comparing eval'd strings with code references will give you inaccurate
336       results: a code reference will show a slightly slower execution time
337       than the equivalent eval'd string.
338
339       The real time timing is done using time(2) and the granularity is
340       therefore only one second.
341
342       Short tests may produce negative figures because perl can appear to
343       take longer to execute the empty loop than a short test; try:
344
345           timethis(100,'1');
346
347       The system time of the null loop might be slightly more than the system
348       time of the loop with the actual code and therefore the difference
349       might end up being < 0.
350

SEE ALSO

352       Devel::DProf - a Perl code profiler
353

AUTHORS

355       Jarkko Hietaniemi <jhi@iki.fi>, Tim Bunce <Tim.Bunce@ig.co.uk>
356

MODIFICATION HISTORY

358       September 8th, 1994; by Tim Bunce.
359
360       March 28th, 1997; by Hugo van der Sanden: added support for code refer‐
361       ences and the already documented 'debug' method; revamped documenta‐
362       tion.
363
364       April 04-07th, 1997: by Jarkko Hietaniemi, added the run-for-some-time
365       functionality.
366
367       September, 1999; by Barrie Slaymaker: math fixes and accuracy and effi‐
368       ciency tweaks.  Added cmpthese().  A result is now returned from
369       timethese().  Exposed countit() (was runfor()).
370
371       December, 2001; by Nicholas Clark: make timestr() recognise the style
372       'none' and return an empty string. If cmpthese is calling timethese,
373       make it pass the style in. (so that 'none' will suppress output). Make
374       sub new dump its debugging output to STDERR, to be consistent with
375       everything else.  All bugs found while writing a regression test.
376
377       September, 2002; by Jarkko Hietaniemi: add ':hireswallclock' special
378       tag.
379
380       February, 2004; by Chia-liang Kao: make cmpthese and timestr use time
381       statistics for children instead of parent when the style is 'nop'.
382
383
384
385perl v5.8.8                       2001-09-21                    Benchmark(3pm)
Impressum