py-cvs-rel2_1 (Rev 1.2) merge
[python/dscho.git] / Doc / lib / libprofile.tex
blob193f5aae248b8749b8b9500544351b0af0a53f33
1 \chapter{The Python Profiler \label{profile}}
3 \sectionauthor{James Roskind}{}
5 Copyright \copyright{} 1994, by InfoSeek Corporation, all rights reserved.
6 \index{InfoSeek Corporation}
8 Written by James Roskind.\footnote{
9 Updated and converted to \LaTeX\ by Guido van Rossum. The references to
10 the old profiler are left in the text, although it no longer exists.}
12 Permission to use, copy, modify, and distribute this Python software
13 and its associated documentation for any purpose (subject to the
14 restriction in the following sentence) without fee is hereby granted,
15 provided that the above copyright notice appears in all copies, and
16 that both that copyright notice and this permission notice appear in
17 supporting documentation, and that the name of InfoSeek not be used in
18 advertising or publicity pertaining to distribution of the software
19 without specific, written prior permission. This permission is
20 explicitly restricted to the copying and modification of the software
21 to remain in Python, compiled Python, or other languages (such as C)
22 wherein the modified or derived code is exclusively imported into a
23 Python module.
25 INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
26 SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
27 FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION BE LIABLE FOR ANY
28 SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
29 RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
30 CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
31 CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
34 The profiler was written after only programming in Python for 3 weeks.
35 As a result, it is probably clumsy code, but I don't know for sure yet
36 'cause I'm a beginner :-). I did work hard to make the code run fast,
37 so that profiling would be a reasonable thing to do. I tried not to
38 repeat code fragments, but I'm sure I did some stuff in really awkward
39 ways at times. Please send suggestions for improvements to:
40 \email{jar@netscape.com}. I won't promise \emph{any} support. ...but
41 I'd appreciate the feedback.
44 \section{Introduction to the profiler}
45 \nodename{Profiler Introduction}
47 A \dfn{profiler} is a program that describes the run time performance
48 of a program, providing a variety of statistics. This documentation
49 describes the profiler functionality provided in the modules
50 \module{profile} and \module{pstats}. This profiler provides
51 \dfn{deterministic profiling} of any Python programs. It also
52 provides a series of report generation tools to allow users to rapidly
53 examine the results of a profile operation.
54 \index{deterministic profiling}
55 \index{profiling, deterministic}
58 \section{How Is This Profiler Different From The Old Profiler?}
59 \nodename{Profiler Changes}
61 (This section is of historical importance only; the old profiler
62 discussed here was last seen in Python 1.1.)
64 The big changes from old profiling module are that you get more
65 information, and you pay less CPU time. It's not a trade-off, it's a
66 trade-up.
68 To be specific:
70 \begin{description}
72 \item[Bugs removed:]
73 Local stack frame is no longer molested, execution time is now charged
74 to correct functions.
76 \item[Accuracy increased:]
77 Profiler execution time is no longer charged to user's code,
78 calibration for platform is supported, file reads are not done \emph{by}
79 profiler \emph{during} profiling (and charged to user's code!).
81 \item[Speed increased:]
82 Overhead CPU cost was reduced by more than a factor of two (perhaps a
83 factor of five), lightweight profiler module is all that must be
84 loaded, and the report generating module (\module{pstats}) is not needed
85 during profiling.
87 \item[Recursive functions support:]
88 Cumulative times in recursive functions are correctly calculated;
89 recursive entries are counted.
91 \item[Large growth in report generating UI:]
92 Distinct profiles runs can be added together forming a comprehensive
93 report; functions that import statistics take arbitrary lists of
94 files; sorting criteria is now based on keywords (instead of 4 integer
95 options); reports shows what functions were profiled as well as what
96 profile file was referenced; output format has been improved.
98 \end{description}
101 \section{Instant Users Manual \label{profile-instant}}
103 This section is provided for users that ``don't want to read the
104 manual.'' It provides a very brief overview, and allows a user to
105 rapidly perform profiling on an existing application.
107 To profile an application with a main entry point of \samp{foo()}, you
108 would add the following to your module:
110 \begin{verbatim}
111 import profile
112 profile.run('foo()')
113 \end{verbatim}
115 The above action would cause \samp{foo()} to be run, and a series of
116 informative lines (the profile) to be printed. The above approach is
117 most useful when working with the interpreter. If you would like to
118 save the results of a profile into a file for later examination, you
119 can supply a file name as the second argument to the \function{run()}
120 function:
122 \begin{verbatim}
123 import profile
124 profile.run('foo()', 'fooprof')
125 \end{verbatim}
127 The file \file{profile.py} can also be invoked as
128 a script to profile another script. For example:
130 \begin{verbatim}
131 python /usr/local/lib/python1.5/profile.py myscript.py
132 \end{verbatim}
134 When you wish to review the profile, you should use the methods in the
135 \module{pstats} module. Typically you would load the statistics data as
136 follows:
138 \begin{verbatim}
139 import pstats
140 p = pstats.Stats('fooprof')
141 \end{verbatim}
143 The class \class{Stats} (the above code just created an instance of
144 this class) has a variety of methods for manipulating and printing the
145 data that was just read into \samp{p}. When you ran
146 \function{profile.run()} above, what was printed was the result of three
147 method calls:
149 \begin{verbatim}
150 p.strip_dirs().sort_stats(-1).print_stats()
151 \end{verbatim}
153 The first method removed the extraneous path from all the module
154 names. The second method sorted all the entries according to the
155 standard module/line/name string that is printed (this is to comply
156 with the semantics of the old profiler). The third method printed out
157 all the statistics. You might try the following sort calls:
159 \begin{verbatim}
160 p.sort_stats('name')
161 p.print_stats()
162 \end{verbatim}
164 The first call will actually sort the list by function name, and the
165 second call will print out the statistics. The following are some
166 interesting calls to experiment with:
168 \begin{verbatim}
169 p.sort_stats('cumulative').print_stats(10)
170 \end{verbatim}
172 This sorts the profile by cumulative time in a function, and then only
173 prints the ten most significant lines. If you want to understand what
174 algorithms are taking time, the above line is what you would use.
176 If you were looking to see what functions were looping a lot, and
177 taking a lot of time, you would do:
179 \begin{verbatim}
180 p.sort_stats('time').print_stats(10)
181 \end{verbatim}
183 to sort according to time spent within each function, and then print
184 the statistics for the top ten functions.
186 You might also try:
188 \begin{verbatim}
189 p.sort_stats('file').print_stats('__init__')
190 \end{verbatim}
192 This will sort all the statistics by file name, and then print out
193 statistics for only the class init methods ('cause they are spelled
194 with \samp{__init__} in them). As one final example, you could try:
196 \begin{verbatim}
197 p.sort_stats('time', 'cum').print_stats(.5, 'init')
198 \end{verbatim}
200 This line sorts statistics with a primary key of time, and a secondary
201 key of cumulative time, and then prints out some of the statistics.
202 To be specific, the list is first culled down to 50\% (re: \samp{.5})
203 of its original size, then only lines containing \code{init} are
204 maintained, and that sub-sub-list is printed.
206 If you wondered what functions called the above functions, you could
207 now (\samp{p} is still sorted according to the last criteria) do:
209 \begin{verbatim}
210 p.print_callers(.5, 'init')
211 \end{verbatim}
213 and you would get a list of callers for each of the listed functions.
215 If you want more functionality, you're going to have to read the
216 manual, or guess what the following functions do:
218 \begin{verbatim}
219 p.print_callees()
220 p.add('fooprof')
221 \end{verbatim}
223 Invoked as a script, the \module{pstats} module is a statistics
224 browser for reading and examining profile dumps. It has a simple
225 line-oriented interface (implemented using \refmodule{cmd}) and
226 interactive help.
228 \section{What Is Deterministic Profiling?}
229 \nodename{Deterministic Profiling}
231 \dfn{Deterministic profiling} is meant to reflect the fact that all
232 \emph{function call}, \emph{function return}, and \emph{exception} events
233 are monitored, and precise timings are made for the intervals between
234 these events (during which time the user's code is executing). In
235 contrast, \dfn{statistical profiling} (which is not done by this
236 module) randomly samples the effective instruction pointer, and
237 deduces where time is being spent. The latter technique traditionally
238 involves less overhead (as the code does not need to be instrumented),
239 but provides only relative indications of where time is being spent.
241 In Python, since there is an interpreter active during execution, the
242 presence of instrumented code is not required to do deterministic
243 profiling. Python automatically provides a \dfn{hook} (optional
244 callback) for each event. In addition, the interpreted nature of
245 Python tends to add so much overhead to execution, that deterministic
246 profiling tends to only add small processing overhead in typical
247 applications. The result is that deterministic profiling is not that
248 expensive, yet provides extensive run time statistics about the
249 execution of a Python program.
251 Call count statistics can be used to identify bugs in code (surprising
252 counts), and to identify possible inline-expansion points (high call
253 counts). Internal time statistics can be used to identify ``hot
254 loops'' that should be carefully optimized. Cumulative time
255 statistics should be used to identify high level errors in the
256 selection of algorithms. Note that the unusual handling of cumulative
257 times in this profiler allows statistics for recursive implementations
258 of algorithms to be directly compared to iterative implementations.
261 \section{Reference Manual}
263 \declaremodule{standard}{profile}
264 \modulesynopsis{Python profiler}
268 The primary entry point for the profiler is the global function
269 \function{profile.run()}. It is typically used to create any profile
270 information. The reports are formatted and printed using methods of
271 the class \class{pstats.Stats}. The following is a description of all
272 of these standard entry points and functions. For a more in-depth
273 view of some of the code, consider reading the later section on
274 Profiler Extensions, which includes discussion of how to derive
275 ``better'' profilers from the classes presented, or reading the source
276 code for these modules.
278 \begin{funcdesc}{run}{string\optional{, filename\optional{, ...}}}
280 This function takes a single argument that has can be passed to the
281 \keyword{exec} statement, and an optional file name. In all cases this
282 routine attempts to \keyword{exec} its first argument, and gather profiling
283 statistics from the execution. If no file name is present, then this
284 function automatically prints a simple profiling report, sorted by the
285 standard name string (file/line/function-name) that is presented in
286 each line. The following is a typical output from such a call:
288 \begin{verbatim}
289 main()
290 2706 function calls (2004 primitive calls) in 4.504 CPU seconds
292 Ordered by: standard name
294 ncalls tottime percall cumtime percall filename:lineno(function)
295 2 0.006 0.003 0.953 0.477 pobject.py:75(save_objects)
296 43/3 0.533 0.012 0.749 0.250 pobject.py:99(evaluate)
298 \end{verbatim}
300 The first line indicates that this profile was generated by the call:\\
301 \code{profile.run('main()')}, and hence the exec'ed string is
302 \code{'main()'}. The second line indicates that 2706 calls were
303 monitored. Of those calls, 2004 were \dfn{primitive}. We define
304 \dfn{primitive} to mean that the call was not induced via recursion.
305 The next line: \code{Ordered by:\ standard name}, indicates that
306 the text string in the far right column was used to sort the output.
307 The column headings include:
309 \begin{description}
311 \item[ncalls ]
312 for the number of calls,
314 \item[tottime ]
315 for the total time spent in the given function (and excluding time
316 made in calls to sub-functions),
318 \item[percall ]
319 is the quotient of \code{tottime} divided by \code{ncalls}
321 \item[cumtime ]
322 is the total time spent in this and all subfunctions (from invocation
323 till exit). This figure is accurate \emph{even} for recursive
324 functions.
326 \item[percall ]
327 is the quotient of \code{cumtime} divided by primitive calls
329 \item[filename:lineno(function) ]
330 provides the respective data of each function
332 \end{description}
334 When there are two numbers in the first column (for example,
335 \samp{43/3}), then the latter is the number of primitive calls, and
336 the former is the actual number of calls. Note that when the function
337 does not recurse, these two values are the same, and only the single
338 figure is printed.
340 \end{funcdesc}
342 Analysis of the profiler data is done using this class from the
343 \module{pstats} module:
345 % now switch modules....
346 % (This \stmodindex use may be hard to change ;-( )
347 \stmodindex{pstats}
349 \begin{classdesc}{Stats}{filename\optional{, ...}}
350 This class constructor creates an instance of a ``statistics object''
351 from a \var{filename} (or set of filenames). \class{Stats} objects are
352 manipulated by methods, in order to print useful reports.
354 The file selected by the above constructor must have been created by
355 the corresponding version of \module{profile}. To be specific, there is
356 \emph{no} file compatibility guaranteed with future versions of this
357 profiler, and there is no compatibility with files produced by other
358 profilers (such as the old system profiler).
360 If several files are provided, all the statistics for identical
361 functions will be coalesced, so that an overall view of several
362 processes can be considered in a single report. If additional files
363 need to be combined with data in an existing \class{Stats} object, the
364 \method{add()} method can be used.
365 \end{classdesc}
368 \subsection{The \class{Stats} Class \label{profile-stats}}
370 \class{Stats} objects have the following methods:
372 \begin{methoddesc}[Stats]{strip_dirs}{}
373 This method for the \class{Stats} class removes all leading path
374 information from file names. It is very useful in reducing the size
375 of the printout to fit within (close to) 80 columns. This method
376 modifies the object, and the stripped information is lost. After
377 performing a strip operation, the object is considered to have its
378 entries in a ``random'' order, as it was just after object
379 initialization and loading. If \method{strip_dirs()} causes two
380 function names to be indistinguishable (they are on the same
381 line of the same filename, and have the same function name), then the
382 statistics for these two entries are accumulated into a single entry.
383 \end{methoddesc}
386 \begin{methoddesc}[Stats]{add}{filename\optional{, ...}}
387 This method of the \class{Stats} class accumulates additional
388 profiling information into the current profiling object. Its
389 arguments should refer to filenames created by the corresponding
390 version of \function{profile.run()}. Statistics for identically named
391 (re: file, line, name) functions are automatically accumulated into
392 single function statistics.
393 \end{methoddesc}
395 \begin{methoddesc}[Stats]{sort_stats}{key\optional{, ...}}
396 This method modifies the \class{Stats} object by sorting it according
397 to the supplied criteria. The argument is typically a string
398 identifying the basis of a sort (example: \code{'time'} or
399 \code{'name'}).
401 When more than one key is provided, then additional keys are used as
402 secondary criteria when the there is equality in all keys selected
403 before them. For example, \samp{sort_stats('name', 'file')} will sort
404 all the entries according to their function name, and resolve all ties
405 (identical function names) by sorting by file name.
407 Abbreviations can be used for any key names, as long as the
408 abbreviation is unambiguous. The following are the keys currently
409 defined:
411 \begin{tableii}{l|l}{code}{Valid Arg}{Meaning}
412 \lineii{'calls'}{call count}
413 \lineii{'cumulative'}{cumulative time}
414 \lineii{'file'}{file name}
415 \lineii{'module'}{file name}
416 \lineii{'pcalls'}{primitive call count}
417 \lineii{'line'}{line number}
418 \lineii{'name'}{function name}
419 \lineii{'nfl'}{name/file/line}
420 \lineii{'stdname'}{standard name}
421 \lineii{'time'}{internal time}
422 \end{tableii}
424 Note that all sorts on statistics are in descending order (placing
425 most time consuming items first), where as name, file, and line number
426 searches are in ascending order (alphabetical). The subtle
427 distinction between \code{'nfl'} and \code{'stdname'} is that the
428 standard name is a sort of the name as printed, which means that the
429 embedded line numbers get compared in an odd way. For example, lines
430 3, 20, and 40 would (if the file names were the same) appear in the
431 string order 20, 3 and 40. In contrast, \code{'nfl'} does a numeric
432 compare of the line numbers. In fact, \code{sort_stats('nfl')} is the
433 same as \code{sort_stats('name', 'file', 'line')}.
435 For compatibility with the old profiler, the numeric arguments
436 \code{-1}, \code{0}, \code{1}, and \code{2} are permitted. They are
437 interpreted as \code{'stdname'}, \code{'calls'}, \code{'time'}, and
438 \code{'cumulative'} respectively. If this old style format (numeric)
439 is used, only one sort key (the numeric key) will be used, and
440 additional arguments will be silently ignored.
441 \end{methoddesc}
444 \begin{methoddesc}[Stats]{reverse_order}{}
445 This method for the \class{Stats} class reverses the ordering of the basic
446 list within the object. This method is provided primarily for
447 compatibility with the old profiler. Its utility is questionable
448 now that ascending vs descending order is properly selected based on
449 the sort key of choice.
450 \end{methoddesc}
452 \begin{methoddesc}[Stats]{print_stats}{\optional{restriction, \moreargs}}
453 This method for the \class{Stats} class prints out a report as described
454 in the \function{profile.run()} definition.
456 The order of the printing is based on the last \method{sort_stats()}
457 operation done on the object (subject to caveats in \method{add()} and
458 \method{strip_dirs()}.
460 The arguments provided (if any) can be used to limit the list down to
461 the significant entries. Initially, the list is taken to be the
462 complete set of profiled functions. Each restriction is either an
463 integer (to select a count of lines), or a decimal fraction between
464 0.0 and 1.0 inclusive (to select a percentage of lines), or a regular
465 expression (to pattern match the standard name that is printed; as of
466 Python 1.5b1, this uses the Perl-style regular expression syntax
467 defined by the \refmodule{re} module). If several restrictions are
468 provided, then they are applied sequentially. For example:
470 \begin{verbatim}
471 print_stats(.1, 'foo:')
472 \end{verbatim}
474 would first limit the printing to first 10\% of list, and then only
475 print functions that were part of filename \samp{.*foo:}. In
476 contrast, the command:
478 \begin{verbatim}
479 print_stats('foo:', .1)
480 \end{verbatim}
482 would limit the list to all functions having file names \samp{.*foo:},
483 and then proceed to only print the first 10\% of them.
484 \end{methoddesc}
487 \begin{methoddesc}[Stats]{print_callers}{\optional{restriction, \moreargs}}
488 This method for the \class{Stats} class prints a list of all functions
489 that called each function in the profiled database. The ordering is
490 identical to that provided by \method{print_stats()}, and the definition
491 of the restricting argument is also identical. For convenience, a
492 number is shown in parentheses after each caller to show how many
493 times this specific call was made. A second non-parenthesized number
494 is the cumulative time spent in the function at the right.
495 \end{methoddesc}
497 \begin{methoddesc}[Stats]{print_callees}{\optional{restriction, \moreargs}}
498 This method for the \class{Stats} class prints a list of all function
499 that were called by the indicated function. Aside from this reversal
500 of direction of calls (re: called vs was called by), the arguments and
501 ordering are identical to the \method{print_callers()} method.
502 \end{methoddesc}
504 \begin{methoddesc}[Stats]{ignore}{}
505 \deprecated{1.5.1}{This is not needed in modern versions of
506 Python.\footnote{
507 This was once necessary, when Python would print any unused expression
508 result that was not \code{None}. The method is still defined for
509 backward compatibility.}}
510 \end{methoddesc}
513 \section{Limitations \label{profile-limits}}
515 There are two fundamental limitations on this profiler. The first is
516 that it relies on the Python interpreter to dispatch \dfn{call},
517 \dfn{return}, and \dfn{exception} events. Compiled \C{} code does not
518 get interpreted, and hence is ``invisible'' to the profiler. All time
519 spent in \C{} code (including built-in functions) will be charged to the
520 Python function that invoked the \C{} code. If the \C{} code calls out
521 to some native Python code, then those calls will be profiled
522 properly.
524 The second limitation has to do with accuracy of timing information.
525 There is a fundamental problem with deterministic profilers involving
526 accuracy. The most obvious restriction is that the underlying ``clock''
527 is only ticking at a rate (typically) of about .001 seconds. Hence no
528 measurements will be more accurate that that underlying clock. If
529 enough measurements are taken, then the ``error'' will tend to average
530 out. Unfortunately, removing this first error induces a second source
531 of error...
533 The second problem is that it ``takes a while'' from when an event is
534 dispatched until the profiler's call to get the time actually
535 \emph{gets} the state of the clock. Similarly, there is a certain lag
536 when exiting the profiler event handler from the time that the clock's
537 value was obtained (and then squirreled away), until the user's code
538 is once again executing. As a result, functions that are called many
539 times, or call many functions, will typically accumulate this error.
540 The error that accumulates in this fashion is typically less than the
541 accuracy of the clock (less than one clock tick), but it
542 \emph{can} accumulate and become very significant. This profiler
543 provides a means of calibrating itself for a given platform so that
544 this error can be probabilistically (on the average) removed.
545 After the profiler is calibrated, it will be more accurate (in a least
546 square sense), but it will sometimes produce negative numbers (when
547 call counts are exceptionally low, and the gods of probability work
548 against you :-). ) Do \emph{not} be alarmed by negative numbers in
549 the profile. They should \emph{only} appear if you have calibrated
550 your profiler, and the results are actually better than without
551 calibration.
554 \section{Calibration \label{profile-calibration}}
556 The profiler class has a hard coded constant that is added to each
557 event handling time to compensate for the overhead of calling the time
558 function, and socking away the results. The following procedure can
559 be used to obtain this constant for a given platform (see discussion
560 in section Limitations above).
562 \begin{verbatim}
563 import profile
564 pr = profile.Profile()
565 print pr.calibrate(100)
566 print pr.calibrate(100)
567 print pr.calibrate(100)
568 \end{verbatim}
570 The argument to \method{calibrate()} is the number of times to try to
571 do the sample calls to get the CPU times. If your computer is
572 \emph{very} fast, you might have to do:
574 \begin{verbatim}
575 pr.calibrate(1000)
576 \end{verbatim}
578 or even:
580 \begin{verbatim}
581 pr.calibrate(10000)
582 \end{verbatim}
584 The object of this exercise is to get a fairly consistent result.
585 When you have a consistent answer, you are ready to use that number in
586 the source code. For a Sun Sparcstation 1000 running Solaris 2.3, the
587 magical number is about .00053. If you have a choice, you are better
588 off with a smaller constant, and your results will ``less often'' show
589 up as negative in profile statistics.
591 The following shows how the trace_dispatch() method in the Profile
592 class should be modified to install the calibration constant on a Sun
593 Sparcstation 1000:
595 \begin{verbatim}
596 def trace_dispatch(self, frame, event, arg):
597 t = self.timer()
598 t = t[0] + t[1] - self.t - .00053 # Calibration constant
600 if self.dispatch[event](frame,t):
601 t = self.timer()
602 self.t = t[0] + t[1]
603 else:
604 r = self.timer()
605 self.t = r[0] + r[1] - t # put back unrecorded delta
606 return
607 \end{verbatim}
609 Note that if there is no calibration constant, then the line
610 containing the callibration constant should simply say:
612 \begin{verbatim}
613 t = t[0] + t[1] - self.t # no calibration constant
614 \end{verbatim}
616 You can also achieve the same results using a derived class (and the
617 profiler will actually run equally fast!!), but the above method is
618 the simplest to use. I could have made the profiler ``self
619 calibrating,'' but it would have made the initialization of the
620 profiler class slower, and would have required some \emph{very} fancy
621 coding, or else the use of a variable where the constant \samp{.00053}
622 was placed in the code shown. This is a \strong{VERY} critical
623 performance section, and there is no reason to use a variable lookup
624 at this point, when a constant can be used.
627 \section{Extensions --- Deriving Better Profilers}
628 \nodename{Profiler Extensions}
630 The \class{Profile} class of module \module{profile} was written so that
631 derived classes could be developed to extend the profiler. Rather
632 than describing all the details of such an effort, I'll just present
633 the following two examples of derived classes that can be used to do
634 profiling. If the reader is an avid Python programmer, then it should
635 be possible to use these as a model and create similar (and perchance
636 better) profile classes.
638 If all you want to do is change how the timer is called, or which
639 timer function is used, then the basic class has an option for that in
640 the constructor for the class. Consider passing the name of a
641 function to call into the constructor:
643 \begin{verbatim}
644 pr = profile.Profile(your_time_func)
645 \end{verbatim}
647 The resulting profiler will call \code{your_time_func()} instead of
648 \function{os.times()}. The function should return either a single number
649 or a list of numbers (like what \function{os.times()} returns). If the
650 function returns a single time number, or the list of returned numbers
651 has length 2, then you will get an especially fast version of the
652 dispatch routine.
654 Be warned that you \emph{should} calibrate the profiler class for the
655 timer function that you choose. For most machines, a timer that
656 returns a lone integer value will provide the best results in terms of
657 low overhead during profiling. (\function{os.times()} is
658 \emph{pretty} bad, as it returns a tuple of floating point values,
659 so all arithmetic is floating point in the profiler!). If you want to
660 substitute a better timer in the cleanest fashion, you should derive a
661 class, and simply put in the replacement dispatch method that better
662 handles your timer call, along with the appropriate calibration
663 constant.
665 Note that subclasses which override any of the
666 \method{trace_dispatch_call()}, \method{trace_dispatch_exception()},
667 or \method{trace_dispatch_return()} methods also need to specify a
668 dispatch table as well. The table, named \member{dispatch}, should
669 have the three keys \code{'call'}, \code{'exception'}, and
670 \code{'return'}, each giving the function of the corresponding
671 handler. Note that best performance is achieved by using the
672 \emph{function} objects for the handlers and not bound methods. This
673 is preferred since calling a simple function object executes less code
674 in the runtime than calling either bound or unbound methods. For
675 example, if the derived profiler overrides only one method, the
676 \member{dispatch} table can be built like this:
678 \begin{verbatim}
679 from profile import Profile
681 class MyProfiler(Profile):
682 def trace_dispath_call(self, frame, t):
683 # do something interesting here
686 dispatch = {
687 'call': trace_dispatch_call,
688 'exception': Profile.__dict__['trace_dispatch_exception'],
689 'return': Profile.__dict__['trace_dispatch_return'],
691 \end{verbatim}
694 \subsection{OldProfile Class \label{profile-old}}
696 The following derived profiler simulates the old style profiler,
697 providing errant results on recursive functions. The reason for the
698 usefulness of this profiler is that it runs faster (less
699 overhead) than the new profiler. It still creates all the caller
700 stats, and is quite useful when there is \emph{no} recursion in the
701 user's code. It is also a lot more accurate than the old profiler, as
702 it does not charge all its overhead time to the user's code.
704 \begin{verbatim}
705 class OldProfile(Profile):
707 def trace_dispatch_exception(self, frame, t):
708 rt, rtt, rct, rfn, rframe, rcur = self.cur
709 if rcur and not rframe is frame:
710 return self.trace_dispatch_return(rframe, t)
711 return 0
713 def trace_dispatch_call(self, frame, t):
714 fn = `frame.f_code`
716 self.cur = (t, 0, 0, fn, frame, self.cur)
717 if self.timings.has_key(fn):
718 tt, ct, callers = self.timings[fn]
719 self.timings[fn] = tt, ct, callers
720 else:
721 self.timings[fn] = 0, 0, {}
722 return 1
724 def trace_dispatch_return(self, frame, t):
725 rt, rtt, rct, rfn, frame, rcur = self.cur
726 rtt = rtt + t
727 sft = rtt + rct
729 pt, ptt, pct, pfn, pframe, pcur = rcur
730 self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur
732 tt, ct, callers = self.timings[rfn]
733 if callers.has_key(pfn):
734 callers[pfn] = callers[pfn] + 1
735 else:
736 callers[pfn] = 1
737 self.timings[rfn] = tt+rtt, ct + sft, callers
739 return 1
741 dispatch = {
742 "call": trace_dispatch_call,
743 "exception": trace_dispatch_exception,
744 "return": trace_dispatch_return,
747 def snapshot_stats(self):
748 self.stats = {}
749 for func in self.timings.keys():
750 tt, ct, callers = self.timings[func]
751 callers = callers.copy()
752 nc = 0
753 for func_caller in callers.keys():
754 nc = nc + callers[func_caller]
755 self.stats[func] = nc, nc, tt, ct, callers
756 \end{verbatim}
759 \subsection{HotProfile Class \label{profile-HotProfile}}
761 This profiler is the fastest derived profile example. It does not
762 calculate caller-callee relationships, and does not calculate
763 cumulative time under a function. It only calculates time spent in a
764 function, so it runs very quickly (re: very low overhead). In truth,
765 the basic profiler is so fast, that is probably not worth the savings
766 to give up the data, but this class still provides a nice example.
768 \begin{verbatim}
769 class HotProfile(Profile):
771 def trace_dispatch_exception(self, frame, t):
772 rt, rtt, rfn, rframe, rcur = self.cur
773 if rcur and not rframe is frame:
774 return self.trace_dispatch_return(rframe, t)
775 return 0
777 def trace_dispatch_call(self, frame, t):
778 self.cur = (t, 0, frame, self.cur)
779 return 1
781 def trace_dispatch_return(self, frame, t):
782 rt, rtt, frame, rcur = self.cur
784 rfn = `frame.f_code`
786 pt, ptt, pframe, pcur = rcur
787 self.cur = pt, ptt+rt, pframe, pcur
789 if self.timings.has_key(rfn):
790 nc, tt = self.timings[rfn]
791 self.timings[rfn] = nc + 1, rt + rtt + tt
792 else:
793 self.timings[rfn] = 1, rt + rtt
795 return 1
797 dispatch = {
798 "call": trace_dispatch_call,
799 "exception": trace_dispatch_exception,
800 "return": trace_dispatch_return,
803 def snapshot_stats(self):
804 self.stats = {}
805 for func in self.timings.keys():
806 nc, tt = self.timings[func]
807 self.stats[func] = nc, nc, tt, 0, {}
808 \end{verbatim}