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