blob: 52156a3126f5b48c25aa89e82f3e13cf85399202 [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
Guido van Rossum364e6431997-11-18 15:28:46 +000060(This section is of historical importance only; the old profiler
61discussed here was last seen in Python 1.1.)
62
Guido van Rossumdf804f81995-03-02 12:38:39 +000063The big changes from old profiling module are that you get more
64information, and you pay less CPU time. It's not a trade-off, it's a
65trade-up.
66
67To be specific:
68
69\begin{description}
70
71\item[Bugs removed:]
72Local stack frame is no longer molested, execution time is now charged
73to correct functions.
74
75\item[Accuracy increased:]
76Profiler execution time is no longer charged to user's code,
77calibration for platform is supported, file reads are not done \emph{by}
78profiler \emph{during} profiling (and charged to user's code!).
79
80\item[Speed increased:]
81Overhead CPU cost was reduced by more than a factor of two (perhaps a
82factor of five), lightweight profiler module is all that must be
83loaded, and the report generating module (\code{pstats}) is not needed
84during profiling.
85
86\item[Recursive functions support:]
87Cumulative times in recursive functions are correctly calculated;
88recursive entries are counted.
89
90\item[Large growth in report generating UI:]
91Distinct profiles runs can be added together forming a comprehensive
92report; functions that import statistics take arbitrary lists of
93files; sorting criteria is now based on keywords (instead of 4 integer
94options); reports shows what functions were profiled as well as what
95profile file was referenced; output format has been improved.
96
97\end{description}
98
99
100\section{Instant Users Manual}
101
102This section is provided for users that ``don't want to read the
103manual.'' It provides a very brief overview, and allows a user to
104rapidly perform profiling on an existing application.
105
106To profile an application with a main entry point of \samp{foo()}, you
107would add the following to your module:
108
Guido van Rossume47da0a1997-07-17 16:34:52 +0000109\bcode\begin{verbatim}
110import profile
111profile.run("foo()")
112\end{verbatim}\ecode
113%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000114The above action would cause \samp{foo()} to be run, and a series of
115informative lines (the profile) to be printed. The above approach is
116most useful when working with the interpreter. If you would like to
117save the results of a profile into a file for later examination, you
118can supply a file name as the second argument to the \code{run()}
119function:
120
Guido van Rossume47da0a1997-07-17 16:34:52 +0000121\bcode\begin{verbatim}
122import profile
123profile.run("foo()", 'fooprof')
124\end{verbatim}\ecode
125%
Guido van Rossumbac80021997-06-02 17:29:12 +0000126\code{profile.py} can also be invoked as
127a script to profile another script. For example:
128\code{python /usr/local/lib/python1.4/profile.py myscript.py}
129
Guido van Rossumdf804f81995-03-02 12:38:39 +0000130When you wish to review the profile, you should use the methods in the
131\code{pstats} module. Typically you would load the statistics data as
132follows:
133
Guido van Rossume47da0a1997-07-17 16:34:52 +0000134\bcode\begin{verbatim}
135import pstats
136p = pstats.Stats('fooprof')
137\end{verbatim}\ecode
138%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000139The class \code{Stats} (the above code just created an instance of
140this class) has a variety of methods for manipulating and printing the
141data that was just read into \samp{p}. When you ran
142\code{profile.run()} above, what was printed was the result of three
143method calls:
144
Guido van Rossume47da0a1997-07-17 16:34:52 +0000145\bcode\begin{verbatim}
146p.strip_dirs().sort_stats(-1).print_stats()
147\end{verbatim}\ecode
148%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000149The first method removed the extraneous path from all the module
150names. The second method sorted all the entries according to the
151standard module/line/name string that is printed (this is to comply
152with the semantics of the old profiler). The third method printed out
153all the statistics. You might try the following sort calls:
154
Guido van Rossume47da0a1997-07-17 16:34:52 +0000155\bcode\begin{verbatim}
156p.sort_stats('name')
157p.print_stats()
158\end{verbatim}\ecode
159%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000160The first call will actually sort the list by function name, and the
161second call will print out the statistics. The following are some
162interesting calls to experiment with:
163
Guido van Rossume47da0a1997-07-17 16:34:52 +0000164\bcode\begin{verbatim}
165p.sort_stats('cumulative').print_stats(10)
166\end{verbatim}\ecode
167%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000168This sorts the profile by cumulative time in a function, and then only
169prints the ten most significant lines. If you want to understand what
170algorithms are taking time, the above line is what you would use.
171
172If you were looking to see what functions were looping a lot, and
173taking a lot of time, you would do:
174
Guido van Rossume47da0a1997-07-17 16:34:52 +0000175\bcode\begin{verbatim}
176p.sort_stats('time').print_stats(10)
177\end{verbatim}\ecode
178%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000179to sort according to time spent within each function, and then print
180the statistics for the top ten functions.
181
182You might also try:
183
Guido van Rossume47da0a1997-07-17 16:34:52 +0000184\bcode\begin{verbatim}
185p.sort_stats('file').print_stats('__init__')
186\end{verbatim}\ecode
187%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000188This will sort all the statistics by file name, and then print out
189statistics for only the class init methods ('cause they are spelled
190with \code{__init__} in them). As one final example, you could try:
191
Guido van Rossume47da0a1997-07-17 16:34:52 +0000192\bcode\begin{verbatim}
193p.sort_stats('time', 'cum').print_stats(.5, 'init')
194\end{verbatim}\ecode
195%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000196This line sorts statistics with a primary key of time, and a secondary
197key of cumulative time, and then prints out some of the statistics.
198To be specific, the list is first culled down to 50\% (re: \samp{.5})
199of its original size, then only lines containing \code{init} are
200maintained, and that sub-sub-list is printed.
201
202If you wondered what functions called the above functions, you could
203now (\samp{p} is still sorted according to the last criteria) do:
204
Guido van Rossume47da0a1997-07-17 16:34:52 +0000205\bcode\begin{verbatim}
206p.print_callers(.5, 'init')
207\end{verbatim}\ecode
208%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000209and you would get a list of callers for each of the listed functions.
210
211If you want more functionality, you're going to have to read the
212manual, or guess what the following functions do:
213
Guido van Rossume47da0a1997-07-17 16:34:52 +0000214\bcode\begin{verbatim}
215p.print_callees()
216p.add('fooprof')
217\end{verbatim}\ecode
218%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000219\section{What Is Deterministic Profiling?}
Guido van Rossum86cb0921995-03-20 12:59:56 +0000220\nodename{Deterministic Profiling}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000221
222\dfn{Deterministic profiling} is meant to reflect the fact that all
223\dfn{function call}, \dfn{function return}, and \dfn{exception} events
224are monitored, and precise timings are made for the intervals between
225these events (during which time the user's code is executing). In
226contrast, \dfn{statistical profiling} (which is not done by this
227module) randomly samples the effective instruction pointer, and
228deduces where time is being spent. The latter technique traditionally
229involves less overhead (as the code does not need to be instrumented),
230but provides only relative indications of where time is being spent.
231
232In Python, since there is an interpreter active during execution, the
233presence of instrumented code is not required to do deterministic
234profiling. Python automatically provides a \dfn{hook} (optional
235callback) for each event. In addition, the interpreted nature of
236Python tends to add so much overhead to execution, that deterministic
237profiling tends to only add small processing overhead in typical
238applications. The result is that deterministic profiling is not that
239expensive, yet provides extensive run time statistics about the
240execution of a Python program.
241
242Call count statistics can be used to identify bugs in code (surprising
243counts), and to identify possible inline-expansion points (high call
244counts). Internal time statistics can be used to identify ``hot
245loops'' that should be carefully optimized. Cumulative time
246statistics should be used to identify high level errors in the
247selection of algorithms. Note that the unusual handling of cumulative
248times in this profiler allows statistics for recursive implementations
249of algorithms to be directly compared to iterative implementations.
250
251
252\section{Reference Manual}
253
Guido van Rossum470be141995-03-17 16:07:09 +0000254\renewcommand{\indexsubitem}{(profiler function)}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000255
256The primary entry point for the profiler is the global function
257\code{profile.run()}. It is typically used to create any profile
258information. The reports are formatted and printed using methods of
259the class \code{pstats.Stats}. The following is a description of all
260of these standard entry points and functions. For a more in-depth
261view of some of the code, consider reading the later section on
262Profiler Extensions, which includes discussion of how to derive
263``better'' profilers from the classes presented, or reading the source
264code for these modules.
265
Guido van Rossum470be141995-03-17 16:07:09 +0000266\begin{funcdesc}{profile.run}{string\optional{\, filename\optional{\, ...}}}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000267
268This function takes a single argument that has can be passed to the
269\code{exec} statement, and an optional file name. In all cases this
270routine attempts to \code{exec} its first argument, and gather profiling
271statistics from the execution. If no file name is present, then this
272function automatically prints a simple profiling report, sorted by the
273standard name string (file/line/function-name) that is presented in
274each line. The following is a typical output from such a call:
275
Guido van Rossum96628a91995-04-10 11:34:00 +0000276\small{
Guido van Rossume47da0a1997-07-17 16:34:52 +0000277\bcode\begin{verbatim}
Guido van Rossum96628a91995-04-10 11:34:00 +0000278 main()
279 2706 function calls (2004 primitive calls) in 4.504 CPU seconds
Guido van Rossumdf804f81995-03-02 12:38:39 +0000280
Guido van Rossum96628a91995-04-10 11:34:00 +0000281Ordered by: standard name
Guido van Rossumdf804f81995-03-02 12:38:39 +0000282
Guido van Rossum96628a91995-04-10 11:34:00 +0000283ncalls tottime percall cumtime percall filename:lineno(function)
284 2 0.006 0.003 0.953 0.477 pobject.py:75(save_objects)
285 43/3 0.533 0.012 0.749 0.250 pobject.py:99(evaluate)
286 ...
Guido van Rossume47da0a1997-07-17 16:34:52 +0000287\end{verbatim}\ecode
Guido van Rossum96628a91995-04-10 11:34:00 +0000288}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000289
290The first line indicates that this profile was generated by the call:\\
291\code{profile.run('main()')}, and hence the exec'ed string is
292\code{'main()'}. The second line indicates that 2706 calls were
293monitored. Of those calls, 2004 were \dfn{primitive}. We define
294\dfn{primitive} to mean that the call was not induced via recursion.
295The next line: \code{Ordered by:\ standard name}, indicates that
296the text string in the far right column was used to sort the output.
297The column headings include:
298
299\begin{description}
300
301\item[ncalls ]
302for the number of calls,
303
304\item[tottime ]
305for the total time spent in the given function (and excluding time
306made in calls to sub-functions),
307
308\item[percall ]
309is the quotient of \code{tottime} divided by \code{ncalls}
310
311\item[cumtime ]
312is the total time spent in this and all subfunctions (i.e., from
313invocation till exit). This figure is accurate \emph{even} for recursive
314functions.
315
316\item[percall ]
317is the quotient of \code{cumtime} divided by primitive calls
318
319\item[filename:lineno(function) ]
320provides the respective data of each function
321
322\end{description}
323
324When there are two numbers in the first column (e.g.: \samp{43/3}),
325then the latter is the number of primitive calls, and the former is
326the actual number of calls. Note that when the function does not
327recurse, these two values are the same, and only the single figure is
328printed.
Guido van Rossum96628a91995-04-10 11:34:00 +0000329
Guido van Rossumdf804f81995-03-02 12:38:39 +0000330\end{funcdesc}
331
332\begin{funcdesc}{pstats.Stats}{filename\optional{\, ...}}
333This class constructor creates an instance of a ``statistics object''
334from a \var{filename} (or set of filenames). \code{Stats} objects are
335manipulated by methods, in order to print useful reports.
336
337The file selected by the above constructor must have been created by
338the corresponding version of \code{profile}. To be specific, there is
339\emph{NO} file compatibility guaranteed with future versions of this
340profiler, and there is no compatibility with files produced by other
341profilers (e.g., the old system profiler).
342
343If several files are provided, all the statistics for identical
344functions will be coalesced, so that an overall view of several
345processes can be considered in a single report. If additional files
346need to be combined with data in an existing \code{Stats} object, the
347\code{add()} method can be used.
348\end{funcdesc}
349
350
Guido van Rossum470be141995-03-17 16:07:09 +0000351\subsection{The \sectcode{Stats} Class}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000352
353\renewcommand{\indexsubitem}{(Stats method)}
354
355\begin{funcdesc}{strip_dirs}{}
Guido van Rossum470be141995-03-17 16:07:09 +0000356This method for the \code{Stats} class removes all leading path information
Guido van Rossumdf804f81995-03-02 12:38:39 +0000357from file names. It is very useful in reducing the size of the
358printout to fit within (close to) 80 columns. This method modifies
359the object, and the stripped information is lost. After performing a
360strip operation, the object is considered to have its entries in a
361``random'' order, as it was just after object initialization and
362loading. If \code{strip_dirs()} causes two function names to be
363indistinguishable (i.e., they are on the same line of the same
364filename, and have the same function name), then the statistics for
365these two entries are accumulated into a single entry.
366\end{funcdesc}
367
368
369\begin{funcdesc}{add}{filename\optional{\, ...}}
Guido van Rossum470be141995-03-17 16:07:09 +0000370This method of the \code{Stats} class accumulates additional profiling
Guido van Rossumdf804f81995-03-02 12:38:39 +0000371information into the current profiling object. Its arguments should
372refer to filenames created by the corresponding version of
373\code{profile.run()}. Statistics for identically named (re: file,
374line, name) functions are automatically accumulated into single
375function statistics.
376\end{funcdesc}
377
378\begin{funcdesc}{sort_stats}{key\optional{\, ...}}
Guido van Rossum470be141995-03-17 16:07:09 +0000379This method modifies the \code{Stats} object by sorting it according to the
Guido van Rossumdf804f81995-03-02 12:38:39 +0000380supplied criteria. The argument is typically a string identifying the
381basis of a sort (example: \code{"time"} or \code{"name"}).
382
383When more than one key is provided, then additional keys are used as
384secondary criteria when the there is equality in all keys selected
385before them. For example, sort_stats('name', 'file') will sort all
386the entries according to their function name, and resolve all ties
387(identical function names) by sorting by file name.
388
389Abbreviations can be used for any key names, as long as the
390abbreviation is unambiguous. The following are the keys currently
391defined:
392
393\begin{tableii}{|l|l|}{code}{Valid Arg}{Meaning}
394\lineii{"calls"}{call count}
395\lineii{"cumulative"}{cumulative time}
396\lineii{"file"}{file name}
397\lineii{"module"}{file name}
398\lineii{"pcalls"}{primitive call count}
399\lineii{"line"}{line number}
400\lineii{"name"}{function name}
401\lineii{"nfl"}{name/file/line}
402\lineii{"stdname"}{standard name}
403\lineii{"time"}{internal time}
404\end{tableii}
405
406Note that all sorts on statistics are in descending order (placing
407most time consuming items first), where as name, file, and line number
408searches are in ascending order (i.e., alphabetical). The subtle
409distinction between \code{"nfl"} and \code{"stdname"} is that the
410standard name is a sort of the name as printed, which means that the
411embedded line numbers get compared in an odd way. For example, lines
4123, 20, and 40 would (if the file names were the same) appear in the
413string order 20, 3 and 40. In contrast, \code{"nfl"} does a numeric
414compare of the line numbers. In fact, \code{sort_stats("nfl")} is the
415same as \code{sort_stats("name", "file", "line")}.
416
417For compatibility with the old profiler, the numeric arguments
418\samp{-1}, \samp{0}, \samp{1}, and \samp{2} are permitted. They are
419interpreted as \code{"stdname"}, \code{"calls"}, \code{"time"}, and
420\code{"cumulative"} respectively. If this old style format (numeric)
421is used, only one sort key (the numeric key) will be used, and
422additional arguments will be silently ignored.
423\end{funcdesc}
424
425
426\begin{funcdesc}{reverse_order}{}
Guido van Rossum470be141995-03-17 16:07:09 +0000427This method for the \code{Stats} class reverses the ordering of the basic
Guido van Rossumdf804f81995-03-02 12:38:39 +0000428list within the object. This method is provided primarily for
429compatibility with the old profiler. Its utility is questionable
430now that ascending vs descending order is properly selected based on
431the sort key of choice.
432\end{funcdesc}
433
434\begin{funcdesc}{print_stats}{restriction\optional{\, ...}}
Guido van Rossum470be141995-03-17 16:07:09 +0000435This method for the \code{Stats} class prints out a report as described
Guido van Rossumdf804f81995-03-02 12:38:39 +0000436in the \code{profile.run()} definition.
437
438The order of the printing is based on the last \code{sort_stats()}
439operation done on the object (subject to caveats in \code{add()} and
440\code{strip_dirs())}.
441
442The arguments provided (if any) can be used to limit the list down to
443the significant entries. Initially, the list is taken to be the
444complete set of profiled functions. Each restriction is either an
445integer (to select a count of lines), or a decimal fraction between
4460.0 and 1.0 inclusive (to select a percentage of lines), or a regular
Guido van Rossum364e6431997-11-18 15:28:46 +0000447expression (to pattern match the standard name that is printed; as of
448Python 1.5b1, this uses the Perl-style regular expression syntax
449defined by the \code{re} module). If several restrictions are
450provided, then they are applied sequentially. For example:
Guido van Rossumdf804f81995-03-02 12:38:39 +0000451
Guido van Rossume47da0a1997-07-17 16:34:52 +0000452\bcode\begin{verbatim}
453print_stats(.1, "foo:")
454\end{verbatim}\ecode
455%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000456would first limit the printing to first 10\% of list, and then only
457print functions that were part of filename \samp{.*foo:}. In
458contrast, the command:
459
Guido van Rossume47da0a1997-07-17 16:34:52 +0000460\bcode\begin{verbatim}
461print_stats("foo:", .1)
462\end{verbatim}\ecode
463%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000464would limit the list to all functions having file names \samp{.*foo:},
465and then proceed to only print the first 10\% of them.
466\end{funcdesc}
467
468
469\begin{funcdesc}{print_callers}{restrictions\optional{\, ...}}
Guido van Rossum470be141995-03-17 16:07:09 +0000470This method for the \code{Stats} class prints a list of all functions
Guido van Rossumdf804f81995-03-02 12:38:39 +0000471that called each function in the profiled database. The ordering is
472identical to that provided by \code{print_stats()}, and the definition
473of the restricting argument is also identical. For convenience, a
474number is shown in parentheses after each caller to show how many
475times this specific call was made. A second non-parenthesized number
476is the cumulative time spent in the function at the right.
477\end{funcdesc}
478
479\begin{funcdesc}{print_callees}{restrictions\optional{\, ...}}
Guido van Rossum470be141995-03-17 16:07:09 +0000480This method for the \code{Stats} class prints a list of all function
Guido van Rossumdf804f81995-03-02 12:38:39 +0000481that were called by the indicated function. Aside from this reversal
482of direction of calls (re: called vs was called by), the arguments and
483ordering are identical to the \code{print_callers()} method.
484\end{funcdesc}
485
486\begin{funcdesc}{ignore}{}
Guido van Rossum470be141995-03-17 16:07:09 +0000487This method of the \code{Stats} class is used to dispose of the value
Guido van Rossumdf804f81995-03-02 12:38:39 +0000488returned by earlier methods. All standard methods in this class
489return the instance that is being processed, so that the commands can
490be strung together. For example:
491
Guido van Rossume47da0a1997-07-17 16:34:52 +0000492\bcode\begin{verbatim}
Guido van Rossum96628a91995-04-10 11:34:00 +0000493pstats.Stats('foofile').strip_dirs().sort_stats('cum') \
494 .print_stats().ignore()
Guido van Rossume47da0a1997-07-17 16:34:52 +0000495\end{verbatim}\ecode
496%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000497would perform all the indicated functions, but it would not return
Guido van Rossum470be141995-03-17 16:07:09 +0000498the final reference to the \code{Stats} instance.%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000499\footnote{
500This was once necessary, when Python would print any unused expression
501result that was not \code{None}. The method is still defined for
502backward compatibility.
503}
504\end{funcdesc}
505
506
507\section{Limitations}
508
509There are two fundamental limitations on this profiler. The first is
510that it relies on the Python interpreter to dispatch \dfn{call},
511\dfn{return}, and \dfn{exception} events. Compiled C code does not
512get interpreted, and hence is ``invisible'' to the profiler. All time
513spent in C code (including builtin functions) will be charged to the
Guido van Rossumcca8d2b1995-03-22 15:48:46 +0000514Python function that invoked the C code. If the C code calls out
Guido van Rossumdf804f81995-03-02 12:38:39 +0000515to some native Python code, then those calls will be profiled
516properly.
517
518The second limitation has to do with accuracy of timing information.
519There is a fundamental problem with deterministic profilers involving
520accuracy. The most obvious restriction is that the underlying ``clock''
521is only ticking at a rate (typically) of about .001 seconds. Hence no
522measurements will be more accurate that that underlying clock. If
523enough measurements are taken, then the ``error'' will tend to average
524out. Unfortunately, removing this first error induces a second source
525of error...
526
527The second problem is that it ``takes a while'' from when an event is
528dispatched until the profiler's call to get the time actually
529\emph{gets} the state of the clock. Similarly, there is a certain lag
530when exiting the profiler event handler from the time that the clock's
531value was obtained (and then squirreled away), until the user's code
532is once again executing. As a result, functions that are called many
533times, or call many functions, will typically accumulate this error.
534The error that accumulates in this fashion is typically less than the
535accuracy of the clock (i.e., less than one clock tick), but it
536\emph{can} accumulate and become very significant. This profiler
537provides a means of calibrating itself for a given platform so that
538this error can be probabilistically (i.e., on the average) removed.
539After the profiler is calibrated, it will be more accurate (in a least
540square sense), but it will sometimes produce negative numbers (when
541call counts are exceptionally low, and the gods of probability work
542against you :-). ) Do \emph{NOT} be alarmed by negative numbers in
543the profile. They should \emph{only} appear if you have calibrated
544your profiler, and the results are actually better than without
545calibration.
546
547
548\section{Calibration}
549
550The profiler class has a hard coded constant that is added to each
551event handling time to compensate for the overhead of calling the time
552function, and socking away the results. The following procedure can
553be used to obtain this constant for a given platform (see discussion
554in section Limitations above).
555
Guido van Rossume47da0a1997-07-17 16:34:52 +0000556\bcode\begin{verbatim}
557import profile
558pr = profile.Profile()
559pr.calibrate(100)
560pr.calibrate(100)
561pr.calibrate(100)
562\end{verbatim}\ecode
563%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000564The argument to calibrate() is the number of times to try to do the
565sample calls to get the CPU times. If your computer is \emph{very}
566fast, you might have to do:
567
Guido van Rossume47da0a1997-07-17 16:34:52 +0000568\bcode\begin{verbatim}
569pr.calibrate(1000)
570\end{verbatim}\ecode
571%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000572or even:
573
Guido van Rossume47da0a1997-07-17 16:34:52 +0000574\bcode\begin{verbatim}
575pr.calibrate(10000)
576\end{verbatim}\ecode
577%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000578The object of this exercise is to get a fairly consistent result.
579When you have a consistent answer, you are ready to use that number in
580the source code. For a Sun Sparcstation 1000 running Solaris 2.3, the
581magical number is about .00053. If you have a choice, you are better
582off with a smaller constant, and your results will ``less often'' show
583up as negative in profile statistics.
584
585The following shows how the trace_dispatch() method in the Profile
586class should be modified to install the calibration constant on a Sun
587Sparcstation 1000:
588
Guido van Rossume47da0a1997-07-17 16:34:52 +0000589\bcode\begin{verbatim}
590def trace_dispatch(self, frame, event, arg):
591 t = self.timer()
592 t = t[0] + t[1] - self.t - .00053 # Calibration constant
593
594 if self.dispatch[event](frame,t):
Guido van Rossumdf804f81995-03-02 12:38:39 +0000595 t = self.timer()
Guido van Rossume47da0a1997-07-17 16:34:52 +0000596 self.t = t[0] + t[1]
597 else:
598 r = self.timer()
599 self.t = r[0] + r[1] - t # put back unrecorded delta
600 return
601\end{verbatim}\ecode
602%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000603Note that if there is no calibration constant, then the line
604containing the callibration constant should simply say:
605
Guido van Rossume47da0a1997-07-17 16:34:52 +0000606\bcode\begin{verbatim}
607t = t[0] + t[1] - self.t # no calibration constant
608\end{verbatim}\ecode
609%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000610You can also achieve the same results using a derived class (and the
611profiler will actually run equally fast!!), but the above method is
612the simplest to use. I could have made the profiler ``self
613calibrating'', but it would have made the initialization of the
614profiler class slower, and would have required some \emph{very} fancy
615coding, or else the use of a variable where the constant \samp{.00053}
616was placed in the code shown. This is a \strong{VERY} critical
617performance section, and there is no reason to use a variable lookup
618at this point, when a constant can be used.
619
620
Guido van Rossum86cb0921995-03-20 12:59:56 +0000621\section{Extensions --- Deriving Better Profilers}
622\nodename{Profiler Extensions}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000623
624The \code{Profile} class of module \code{profile} was written so that
625derived classes could be developed to extend the profiler. Rather
626than describing all the details of such an effort, I'll just present
627the following two examples of derived classes that can be used to do
628profiling. If the reader is an avid Python programmer, then it should
629be possible to use these as a model and create similar (and perchance
630better) profile classes.
631
632If all you want to do is change how the timer is called, or which
633timer function is used, then the basic class has an option for that in
634the constructor for the class. Consider passing the name of a
635function to call into the constructor:
636
Guido van Rossume47da0a1997-07-17 16:34:52 +0000637\bcode\begin{verbatim}
638pr = profile.Profile(your_time_func)
639\end{verbatim}\ecode
640%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000641The resulting profiler will call \code{your_time_func()} instead of
642\code{os.times()}. The function should return either a single number
643or a list of numbers (like what \code{os.times()} returns). If the
644function returns a single time number, or the list of returned numbers
645has length 2, then you will get an especially fast version of the
646dispatch routine.
647
648Be warned that you \emph{should} calibrate the profiler class for the
649timer function that you choose. For most machines, a timer that
650returns a lone integer value will provide the best results in terms of
651low overhead during profiling. (os.times is \emph{pretty} bad, 'cause
652it returns a tuple of floating point values, so all arithmetic is
653floating point in the profiler!). If you want to substitute a
654better timer in the cleanest fashion, you should derive a class, and
655simply put in the replacement dispatch method that better handles your
656timer call, along with the appropriate calibration constant :-).
657
658
659\subsection{OldProfile Class}
660
661The following derived profiler simulates the old style profiler,
662providing errant results on recursive functions. The reason for the
663usefulness of this profiler is that it runs faster (i.e., less
664overhead) than the old profiler. It still creates all the caller
665stats, and is quite useful when there is \emph{no} recursion in the
666user's code. It is also a lot more accurate than the old profiler, as
667it does not charge all its overhead time to the user's code.
668
Guido van Rossume47da0a1997-07-17 16:34:52 +0000669\bcode\begin{verbatim}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000670class OldProfile(Profile):
671
672 def trace_dispatch_exception(self, frame, t):
673 rt, rtt, rct, rfn, rframe, rcur = self.cur
674 if rcur and not rframe is frame:
675 return self.trace_dispatch_return(rframe, t)
676 return 0
677
678 def trace_dispatch_call(self, frame, t):
679 fn = `frame.f_code`
680
681 self.cur = (t, 0, 0, fn, frame, self.cur)
682 if self.timings.has_key(fn):
683 tt, ct, callers = self.timings[fn]
684 self.timings[fn] = tt, ct, callers
685 else:
686 self.timings[fn] = 0, 0, {}
687 return 1
688
689 def trace_dispatch_return(self, frame, t):
690 rt, rtt, rct, rfn, frame, rcur = self.cur
691 rtt = rtt + t
692 sft = rtt + rct
693
694 pt, ptt, pct, pfn, pframe, pcur = rcur
695 self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur
696
697 tt, ct, callers = self.timings[rfn]
698 if callers.has_key(pfn):
699 callers[pfn] = callers[pfn] + 1
700 else:
701 callers[pfn] = 1
702 self.timings[rfn] = tt+rtt, ct + sft, callers
703
704 return 1
705
706
707 def snapshot_stats(self):
708 self.stats = {}
709 for func in self.timings.keys():
710 tt, ct, callers = self.timings[func]
711 nor_func = self.func_normalize(func)
712 nor_callers = {}
713 nc = 0
714 for func_caller in callers.keys():
715 nor_callers[self.func_normalize(func_caller)]=\
716 callers[func_caller]
717 nc = nc + callers[func_caller]
718 self.stats[nor_func] = nc, nc, tt, ct, nor_callers
Guido van Rossume47da0a1997-07-17 16:34:52 +0000719\end{verbatim}\ecode
720%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000721\subsection{HotProfile Class}
722
723This profiler is the fastest derived profile example. It does not
724calculate caller-callee relationships, and does not calculate
725cumulative time under a function. It only calculates time spent in a
726function, so it runs very quickly (re: very low overhead). In truth,
727the basic profiler is so fast, that is probably not worth the savings
728to give up the data, but this class still provides a nice example.
729
Guido van Rossume47da0a1997-07-17 16:34:52 +0000730\bcode\begin{verbatim}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000731class HotProfile(Profile):
732
733 def trace_dispatch_exception(self, frame, t):
734 rt, rtt, rfn, rframe, rcur = self.cur
735 if rcur and not rframe is frame:
736 return self.trace_dispatch_return(rframe, t)
737 return 0
738
739 def trace_dispatch_call(self, frame, t):
740 self.cur = (t, 0, frame, self.cur)
741 return 1
742
743 def trace_dispatch_return(self, frame, t):
744 rt, rtt, frame, rcur = self.cur
745
746 rfn = `frame.f_code`
747
748 pt, ptt, pframe, pcur = rcur
749 self.cur = pt, ptt+rt, pframe, pcur
750
751 if self.timings.has_key(rfn):
752 nc, tt = self.timings[rfn]
753 self.timings[rfn] = nc + 1, rt + rtt + tt
754 else:
755 self.timings[rfn] = 1, rt + rtt
756
757 return 1
758
759
760 def snapshot_stats(self):
761 self.stats = {}
762 for func in self.timings.keys():
763 nc, tt = self.timings[func]
764 nor_func = self.func_normalize(func)
765 self.stats[nor_func] = nc, nc, tt, 0, {}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000766\end{verbatim}\ecode