blob: 174b51d801056d571dc37e4545dc3e4e135e9ca7 [file] [log] [blame]
Guido van Rossumdf804f81995-03-02 12:38:39 +00001\chapter{The Python Profiler}
Fred Drake31ecd501998-02-18 15:40:11 +00002\label{profile}
Guido van Rossumdf804f81995-03-02 12:38:39 +00003
Fred Drake4b3f0311996-12-13 22:04:31 +00004Copyright \copyright{} 1994, by InfoSeek Corporation, all rights reserved.
Fred Drake5dabeed1998-04-03 07:02:35 +00005\index{InfoSeek Corporation}
Guido van Rossumdf804f81995-03-02 12:38:39 +00006
Fred Drake5dabeed1998-04-03 07:02:35 +00007Written by James Roskind\index{Roskind, James}.%
Guido van Rossumdf804f81995-03-02 12:38:39 +00008\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:
Fred Drake8fa5eb81998-02-27 05:23:37 +000041\email{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
Fred Drake8fa5eb81998-02-27 05:23:37 +000051\module{profile} and \module{pstats}. This profiler provides
Guido van Rossumdf804f81995-03-02 12:38:39 +000052\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.
Fred Drake8fa5eb81998-02-27 05:23:37 +000055\index{deterministic profiling}
56\index{profiling, deterministic}
Guido van Rossumdf804f81995-03-02 12:38:39 +000057
58
59\section{How Is This Profiler Different From The Old Profiler?}
Guido van Rossum86cb0921995-03-20 12:59:56 +000060\nodename{Profiler Changes}
Guido van Rossumdf804f81995-03-02 12:38:39 +000061
Guido van Rossum364e6431997-11-18 15:28:46 +000062(This section is of historical importance only; the old profiler
63discussed here was last seen in Python 1.1.)
64
Guido van Rossumdf804f81995-03-02 12:38:39 +000065The big changes from old profiling module are that you get more
66information, and you pay less CPU time. It's not a trade-off, it's a
67trade-up.
68
69To be specific:
70
71\begin{description}
72
73\item[Bugs removed:]
74Local stack frame is no longer molested, execution time is now charged
75to correct functions.
76
77\item[Accuracy increased:]
78Profiler execution time is no longer charged to user's code,
79calibration for platform is supported, file reads are not done \emph{by}
80profiler \emph{during} profiling (and charged to user's code!).
81
82\item[Speed increased:]
83Overhead CPU cost was reduced by more than a factor of two (perhaps a
84factor of five), lightweight profiler module is all that must be
Fred Drake8fa5eb81998-02-27 05:23:37 +000085loaded, and the report generating module (\module{pstats}) is not needed
Guido van Rossumdf804f81995-03-02 12:38:39 +000086during profiling.
87
88\item[Recursive functions support:]
89Cumulative times in recursive functions are correctly calculated;
90recursive entries are counted.
91
92\item[Large growth in report generating UI:]
93Distinct profiles runs can be added together forming a comprehensive
94report; functions that import statistics take arbitrary lists of
95files; sorting criteria is now based on keywords (instead of 4 integer
96options); reports shows what functions were profiled as well as what
97profile file was referenced; output format has been improved.
98
99\end{description}
100
101
102\section{Instant Users Manual}
103
104This section is provided for users that ``don't want to read the
105manual.'' It provides a very brief overview, and allows a user to
106rapidly perform profiling on an existing application.
107
108To profile an application with a main entry point of \samp{foo()}, you
109would add the following to your module:
110
Fred Drake19479911998-02-13 06:58:54 +0000111\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000112import profile
113profile.run("foo()")
Fred Drake19479911998-02-13 06:58:54 +0000114\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000115%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000116The above action would cause \samp{foo()} to be run, and a series of
117informative lines (the profile) to be printed. The above approach is
118most useful when working with the interpreter. If you would like to
119save the results of a profile into a file for later examination, you
Fred Drake8fa5eb81998-02-27 05:23:37 +0000120can supply a file name as the second argument to the \function{run()}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000121function:
122
Fred Drake19479911998-02-13 06:58:54 +0000123\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000124import profile
125profile.run("foo()", 'fooprof')
Fred Drake19479911998-02-13 06:58:54 +0000126\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000127%
Fred Drake8fa5eb81998-02-27 05:23:37 +0000128The file \file{profile.py} can also be invoked as
Guido van Rossumbac80021997-06-02 17:29:12 +0000129a script to profile another script. For example:
Fred Drake8fa5eb81998-02-27 05:23:37 +0000130
131\begin{verbatim}
Fred Drake5dabeed1998-04-03 07:02:35 +0000132python /usr/local/lib/python1.5/profile.py myscript.py
Fred Drake8fa5eb81998-02-27 05:23:37 +0000133\end{verbatim}
Guido van Rossumbac80021997-06-02 17:29:12 +0000134
Guido van Rossumdf804f81995-03-02 12:38:39 +0000135When you wish to review the profile, you should use the methods in the
Fred Drake8fa5eb81998-02-27 05:23:37 +0000136\module{pstats} module. Typically you would load the statistics data as
Guido van Rossumdf804f81995-03-02 12:38:39 +0000137follows:
138
Fred Drake19479911998-02-13 06:58:54 +0000139\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000140import pstats
141p = pstats.Stats('fooprof')
Fred Drake19479911998-02-13 06:58:54 +0000142\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000143%
Fred Drake8fa5eb81998-02-27 05:23:37 +0000144The class \class{Stats} (the above code just created an instance of
Guido van Rossumdf804f81995-03-02 12:38:39 +0000145this class) has a variety of methods for manipulating and printing the
146data that was just read into \samp{p}. When you ran
Fred Drake8fa5eb81998-02-27 05:23:37 +0000147\function{profile.run()} above, what was printed was the result of three
Guido van Rossumdf804f81995-03-02 12:38:39 +0000148method calls:
149
Fred Drake19479911998-02-13 06:58:54 +0000150\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000151p.strip_dirs().sort_stats(-1).print_stats()
Fred Drake19479911998-02-13 06:58:54 +0000152\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000153%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000154The first method removed the extraneous path from all the module
155names. The second method sorted all the entries according to the
156standard module/line/name string that is printed (this is to comply
157with the semantics of the old profiler). The third method printed out
158all the statistics. You might try the following sort calls:
159
Fred Drake19479911998-02-13 06:58:54 +0000160\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000161p.sort_stats('name')
162p.print_stats()
Fred Drake19479911998-02-13 06:58:54 +0000163\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000164%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000165The first call will actually sort the list by function name, and the
166second call will print out the statistics. The following are some
167interesting calls to experiment with:
168
Fred Drake19479911998-02-13 06:58:54 +0000169\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000170p.sort_stats('cumulative').print_stats(10)
Fred Drake19479911998-02-13 06:58:54 +0000171\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000172%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000173This sorts the profile by cumulative time in a function, and then only
174prints the ten most significant lines. If you want to understand what
175algorithms are taking time, the above line is what you would use.
176
177If you were looking to see what functions were looping a lot, and
178taking a lot of time, you would do:
179
Fred Drake19479911998-02-13 06:58:54 +0000180\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000181p.sort_stats('time').print_stats(10)
Fred Drake19479911998-02-13 06:58:54 +0000182\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000183%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000184to sort according to time spent within each function, and then print
185the statistics for the top ten functions.
186
187You might also try:
188
Fred Drake19479911998-02-13 06:58:54 +0000189\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000190p.sort_stats('file').print_stats('__init__')
Fred Drake19479911998-02-13 06:58:54 +0000191\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000192%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000193This will sort all the statistics by file name, and then print out
194statistics for only the class init methods ('cause they are spelled
Fred Drake8fa5eb81998-02-27 05:23:37 +0000195with \samp{__init__} in them). As one final example, you could try:
Guido van Rossumdf804f81995-03-02 12:38:39 +0000196
Fred Drake19479911998-02-13 06:58:54 +0000197\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000198p.sort_stats('time', 'cum').print_stats(.5, 'init')
Fred Drake19479911998-02-13 06:58:54 +0000199\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000200%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000201This line sorts statistics with a primary key of time, and a secondary
202key of cumulative time, and then prints out some of the statistics.
203To be specific, the list is first culled down to 50\% (re: \samp{.5})
204of its original size, then only lines containing \code{init} are
205maintained, and that sub-sub-list is printed.
206
207If you wondered what functions called the above functions, you could
208now (\samp{p} is still sorted according to the last criteria) do:
209
Fred Drake19479911998-02-13 06:58:54 +0000210\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000211p.print_callers(.5, 'init')
Fred Drake19479911998-02-13 06:58:54 +0000212\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000213
Guido van Rossumdf804f81995-03-02 12:38:39 +0000214and you would get a list of callers for each of the listed functions.
215
216If you want more functionality, you're going to have to read the
217manual, or guess what the following functions do:
218
Fred Drake19479911998-02-13 06:58:54 +0000219\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000220p.print_callees()
221p.add('fooprof')
Fred Drake19479911998-02-13 06:58:54 +0000222\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000223%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000224\section{What Is Deterministic Profiling?}
Guido van Rossum86cb0921995-03-20 12:59:56 +0000225\nodename{Deterministic Profiling}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000226
227\dfn{Deterministic profiling} is meant to reflect the fact that all
228\dfn{function call}, \dfn{function return}, and \dfn{exception} events
229are monitored, and precise timings are made for the intervals between
230these events (during which time the user's code is executing). In
231contrast, \dfn{statistical profiling} (which is not done by this
232module) randomly samples the effective instruction pointer, and
233deduces where time is being spent. The latter technique traditionally
234involves less overhead (as the code does not need to be instrumented),
235but provides only relative indications of where time is being spent.
236
237In Python, since there is an interpreter active during execution, the
238presence of instrumented code is not required to do deterministic
239profiling. Python automatically provides a \dfn{hook} (optional
240callback) for each event. In addition, the interpreted nature of
241Python tends to add so much overhead to execution, that deterministic
242profiling tends to only add small processing overhead in typical
243applications. The result is that deterministic profiling is not that
244expensive, yet provides extensive run time statistics about the
245execution of a Python program.
246
247Call count statistics can be used to identify bugs in code (surprising
248counts), and to identify possible inline-expansion points (high call
249counts). Internal time statistics can be used to identify ``hot
250loops'' that should be carefully optimized. Cumulative time
251statistics should be used to identify high level errors in the
252selection of algorithms. Note that the unusual handling of cumulative
253times in this profiler allows statistics for recursive implementations
254of algorithms to be directly compared to iterative implementations.
255
256
257\section{Reference Manual}
Fred Drake8fe533e1998-03-27 05:27:08 +0000258\stmodindex{profile}
259\label{module-profile}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000260
Guido van Rossumdf804f81995-03-02 12:38:39 +0000261
262The primary entry point for the profiler is the global function
Fred Drake8fa5eb81998-02-27 05:23:37 +0000263\function{profile.run()}. It is typically used to create any profile
Guido van Rossumdf804f81995-03-02 12:38:39 +0000264information. The reports are formatted and printed using methods of
Fred Drake8fa5eb81998-02-27 05:23:37 +0000265the class \class{pstats.Stats}. The following is a description of all
Guido van Rossumdf804f81995-03-02 12:38:39 +0000266of these standard entry points and functions. For a more in-depth
267view of some of the code, consider reading the later section on
268Profiler Extensions, which includes discussion of how to derive
269``better'' profilers from the classes presented, or reading the source
270code for these modules.
271
Fred Drake8fe533e1998-03-27 05:27:08 +0000272\begin{funcdesc}{run}{string\optional{, filename\optional{, ...}}}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000273
274This function takes a single argument that has can be passed to the
Fred Drake8fa5eb81998-02-27 05:23:37 +0000275\keyword{exec} statement, and an optional file name. In all cases this
276routine attempts to \keyword{exec} its first argument, and gather profiling
Guido van Rossumdf804f81995-03-02 12:38:39 +0000277statistics from the execution. If no file name is present, then this
278function automatically prints a simple profiling report, sorted by the
279standard name string (file/line/function-name) that is presented in
280each line. The following is a typical output from such a call:
281
Fred Drake19479911998-02-13 06:58:54 +0000282\begin{verbatim}
Guido van Rossum96628a91995-04-10 11:34:00 +0000283 main()
284 2706 function calls (2004 primitive calls) in 4.504 CPU seconds
Guido van Rossumdf804f81995-03-02 12:38:39 +0000285
Guido van Rossum96628a91995-04-10 11:34:00 +0000286Ordered by: standard name
Guido van Rossumdf804f81995-03-02 12:38:39 +0000287
Guido van Rossum96628a91995-04-10 11:34:00 +0000288ncalls tottime percall cumtime percall filename:lineno(function)
289 2 0.006 0.003 0.953 0.477 pobject.py:75(save_objects)
290 43/3 0.533 0.012 0.749 0.250 pobject.py:99(evaluate)
291 ...
Fred Drake19479911998-02-13 06:58:54 +0000292\end{verbatim}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000293
294The first line indicates that this profile was generated by the call:\\
295\code{profile.run('main()')}, and hence the exec'ed string is
296\code{'main()'}. The second line indicates that 2706 calls were
297monitored. Of those calls, 2004 were \dfn{primitive}. We define
298\dfn{primitive} to mean that the call was not induced via recursion.
299The next line: \code{Ordered by:\ standard name}, indicates that
300the text string in the far right column was used to sort the output.
301The column headings include:
302
303\begin{description}
304
305\item[ncalls ]
306for the number of calls,
307
308\item[tottime ]
309for the total time spent in the given function (and excluding time
310made in calls to sub-functions),
311
312\item[percall ]
313is the quotient of \code{tottime} divided by \code{ncalls}
314
315\item[cumtime ]
316is the total time spent in this and all subfunctions (i.e., from
317invocation till exit). This figure is accurate \emph{even} for recursive
318functions.
319
320\item[percall ]
321is the quotient of \code{cumtime} divided by primitive calls
322
323\item[filename:lineno(function) ]
324provides the respective data of each function
325
326\end{description}
327
328When there are two numbers in the first column (e.g.: \samp{43/3}),
329then the latter is the number of primitive calls, and the former is
330the actual number of calls. Note that when the function does not
331recurse, these two values are the same, and only the single figure is
332printed.
Guido van Rossum96628a91995-04-10 11:34:00 +0000333
Guido van Rossumdf804f81995-03-02 12:38:39 +0000334\end{funcdesc}
335
Fred Drake8fa5eb81998-02-27 05:23:37 +0000336Analysis of the profiler data is done using this class from the
337\module{pstats} module:
338
Fred Drake8fe533e1998-03-27 05:27:08 +0000339% now switch modules....
340\stmodindex{pstats}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000341
Fred Drakecce10901998-03-17 06:33:25 +0000342\begin{classdesc}{Stats}{filename\optional{, ...}}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000343This class constructor creates an instance of a ``statistics object''
Fred Drake8fa5eb81998-02-27 05:23:37 +0000344from a \var{filename} (or set of filenames). \class{Stats} objects are
Guido van Rossumdf804f81995-03-02 12:38:39 +0000345manipulated by methods, in order to print useful reports.
346
347The file selected by the above constructor must have been created by
Fred Drake8fa5eb81998-02-27 05:23:37 +0000348the corresponding version of \module{profile}. To be specific, there is
349\emph{no} file compatibility guaranteed with future versions of this
Guido van Rossumdf804f81995-03-02 12:38:39 +0000350profiler, and there is no compatibility with files produced by other
351profilers (e.g., the old system profiler).
352
353If several files are provided, all the statistics for identical
354functions will be coalesced, so that an overall view of several
355processes can be considered in a single report. If additional files
Fred Drake8fa5eb81998-02-27 05:23:37 +0000356need to be combined with data in an existing \class{Stats} object, the
357\method{add()} method can be used.
358\end{classdesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000359
360
Guido van Rossum470be141995-03-17 16:07:09 +0000361\subsection{The \sectcode{Stats} Class}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000362
Fred Drake19479911998-02-13 06:58:54 +0000363\setindexsubitem{(Stats method)}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000364
Fred Drake8fe533e1998-03-27 05:27:08 +0000365\begin{methoddesc}{strip_dirs}{}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000366This method for the \class{Stats} class removes all leading path
367information from file names. It is very useful in reducing the size
368of the printout to fit within (close to) 80 columns. This method
369modifies the object, and the stripped information is lost. After
370performing a strip operation, the object is considered to have its
371entries in a ``random'' order, as it was just after object
372initialization and loading. If \method{strip_dirs()} causes two
373function names to be indistinguishable (i.e., they are on the same
374line of the same filename, and have the same function name), then the
375statistics for these two entries are accumulated into a single entry.
Fred Drake8fe533e1998-03-27 05:27:08 +0000376\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000377
378
Fred Drake8fe533e1998-03-27 05:27:08 +0000379\begin{methoddesc}{add}{filename\optional{, ...}}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000380This method of the \class{Stats} class accumulates additional
381profiling information into the current profiling object. Its
382arguments should refer to filenames created by the corresponding
383version of \function{profile.run()}. Statistics for identically named
384(re: file, line, name) functions are automatically accumulated into
385single function statistics.
Fred Drake8fe533e1998-03-27 05:27:08 +0000386\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000387
Fred Drake8fe533e1998-03-27 05:27:08 +0000388\begin{methoddesc}{sort_stats}{key\optional{, ...}}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000389This method modifies the \class{Stats} object by sorting it according
390to the supplied criteria. The argument is typically a string
391identifying the basis of a sort (example: \code{"time"} or
392\code{"name"}).
Guido van Rossumdf804f81995-03-02 12:38:39 +0000393
394When more than one key is provided, then additional keys are used as
395secondary criteria when the there is equality in all keys selected
Fred Drake8fa5eb81998-02-27 05:23:37 +0000396before them. For example, \samp{sort_stats('name', 'file')} will sort
397all the entries according to their function name, and resolve all ties
Guido van Rossumdf804f81995-03-02 12:38:39 +0000398(identical function names) by sorting by file name.
399
400Abbreviations can be used for any key names, as long as the
401abbreviation is unambiguous. The following are the keys currently
402defined:
403
404\begin{tableii}{|l|l|}{code}{Valid Arg}{Meaning}
Fred Drake5dabeed1998-04-03 07:02:35 +0000405 \lineii{'calls'}{call count}
406 \lineii{'cumulative'}{cumulative time}
407 \lineii{'file'}{file name}
408 \lineii{'module'}{file name}
409 \lineii{'pcalls'}{primitive call count}
410 \lineii{'line'}{line number}
411 \lineii{'name'}{function name}
412 \lineii{'nfl'}{name/file/line}
413 \lineii{'stdname'}{standard name}
414 \lineii{'time'}{internal time}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000415\end{tableii}
416
417Note that all sorts on statistics are in descending order (placing
418most time consuming items first), where as name, file, and line number
419searches are in ascending order (i.e., alphabetical). The subtle
420distinction between \code{"nfl"} and \code{"stdname"} is that the
421standard name is a sort of the name as printed, which means that the
422embedded line numbers get compared in an odd way. For example, lines
4233, 20, and 40 would (if the file names were the same) appear in the
424string order 20, 3 and 40. In contrast, \code{"nfl"} does a numeric
425compare of the line numbers. In fact, \code{sort_stats("nfl")} is the
426same as \code{sort_stats("name", "file", "line")}.
427
428For compatibility with the old profiler, the numeric arguments
429\samp{-1}, \samp{0}, \samp{1}, and \samp{2} are permitted. They are
430interpreted as \code{"stdname"}, \code{"calls"}, \code{"time"}, and
431\code{"cumulative"} respectively. If this old style format (numeric)
432is used, only one sort key (the numeric key) will be used, and
433additional arguments will be silently ignored.
Fred Drake8fe533e1998-03-27 05:27:08 +0000434\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000435
436
Fred Drake8fe533e1998-03-27 05:27:08 +0000437\begin{methoddesc}{reverse_order}{}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000438This method for the \class{Stats} class reverses the ordering of the basic
Guido van Rossumdf804f81995-03-02 12:38:39 +0000439list within the object. This method is provided primarily for
440compatibility with the old profiler. Its utility is questionable
441now that ascending vs descending order is properly selected based on
442the sort key of choice.
Fred Drake8fe533e1998-03-27 05:27:08 +0000443\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000444
Fred Drake8fe533e1998-03-27 05:27:08 +0000445\begin{methoddesc}{print_stats}{restriction\optional{, ...}}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000446This method for the \class{Stats} class prints out a report as described
447in the \function{profile.run()} definition.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000448
Fred Drake8fa5eb81998-02-27 05:23:37 +0000449The order of the printing is based on the last \method{sort_stats()}
450operation done on the object (subject to caveats in \method{add()} and
451\method{strip_dirs()}.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000452
453The arguments provided (if any) can be used to limit the list down to
454the significant entries. Initially, the list is taken to be the
455complete set of profiled functions. Each restriction is either an
456integer (to select a count of lines), or a decimal fraction between
4570.0 and 1.0 inclusive (to select a percentage of lines), or a regular
Guido van Rossum364e6431997-11-18 15:28:46 +0000458expression (to pattern match the standard name that is printed; as of
459Python 1.5b1, this uses the Perl-style regular expression syntax
Fred Drake8fa5eb81998-02-27 05:23:37 +0000460defined by the \module{re} module). If several restrictions are
Guido van Rossum364e6431997-11-18 15:28:46 +0000461provided, then they are applied sequentially. For example:
Guido van Rossumdf804f81995-03-02 12:38:39 +0000462
Fred Drake19479911998-02-13 06:58:54 +0000463\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000464print_stats(.1, "foo:")
Fred Drake19479911998-02-13 06:58:54 +0000465\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000466
Guido van Rossumdf804f81995-03-02 12:38:39 +0000467would first limit the printing to first 10\% of list, and then only
468print functions that were part of filename \samp{.*foo:}. In
469contrast, the command:
470
Fred Drake19479911998-02-13 06:58:54 +0000471\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000472print_stats("foo:", .1)
Fred Drake19479911998-02-13 06:58:54 +0000473\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000474
Guido van Rossumdf804f81995-03-02 12:38:39 +0000475would limit the list to all functions having file names \samp{.*foo:},
476and then proceed to only print the first 10\% of them.
Fred Drake8fe533e1998-03-27 05:27:08 +0000477\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000478
479
Fred Drake8fe533e1998-03-27 05:27:08 +0000480\begin{methoddesc}{print_callers}{restrictions\optional{, ...}}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000481This method for the \class{Stats} class prints a list of all functions
Guido van Rossumdf804f81995-03-02 12:38:39 +0000482that called each function in the profiled database. The ordering is
Fred Drake8fa5eb81998-02-27 05:23:37 +0000483identical to that provided by \method{print_stats()}, and the definition
Guido van Rossumdf804f81995-03-02 12:38:39 +0000484of the restricting argument is also identical. For convenience, a
485number is shown in parentheses after each caller to show how many
486times this specific call was made. A second non-parenthesized number
487is the cumulative time spent in the function at the right.
Fred Drake8fe533e1998-03-27 05:27:08 +0000488\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000489
Fred Drake8fe533e1998-03-27 05:27:08 +0000490\begin{methoddesc}{print_callees}{restrictions\optional{, ...}}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000491This method for the \class{Stats} class prints a list of all function
Guido van Rossumdf804f81995-03-02 12:38:39 +0000492that were called by the indicated function. Aside from this reversal
493of direction of calls (re: called vs was called by), the arguments and
Fred Drake8fa5eb81998-02-27 05:23:37 +0000494ordering are identical to the \method{print_callers()} method.
Fred Drake8fe533e1998-03-27 05:27:08 +0000495\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000496
Fred Drake8fe533e1998-03-27 05:27:08 +0000497\begin{methoddesc}{ignore}{}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000498This method of the \class{Stats} class is used to dispose of the value
Guido van Rossumdf804f81995-03-02 12:38:39 +0000499returned by earlier methods. All standard methods in this class
500return the instance that is being processed, so that the commands can
501be strung together. For example:
502
Fred Drake19479911998-02-13 06:58:54 +0000503\begin{verbatim}
Guido van Rossum96628a91995-04-10 11:34:00 +0000504pstats.Stats('foofile').strip_dirs().sort_stats('cum') \
505 .print_stats().ignore()
Fred Drake19479911998-02-13 06:58:54 +0000506\end{verbatim}
Fred Drake8fe533e1998-03-27 05:27:08 +0000507
Guido van Rossumdf804f81995-03-02 12:38:39 +0000508would perform all the indicated functions, but it would not return
Fred Drake8fa5eb81998-02-27 05:23:37 +0000509the final reference to the \class{Stats} instance.%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000510\footnote{
511This was once necessary, when Python would print any unused expression
512result that was not \code{None}. The method is still defined for
513backward compatibility.
514}
Fred Drake8fe533e1998-03-27 05:27:08 +0000515\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000516
517
518\section{Limitations}
519
520There are two fundamental limitations on this profiler. The first is
521that it relies on the Python interpreter to dispatch \dfn{call},
Fred Drake8fa5eb81998-02-27 05:23:37 +0000522\dfn{return}, and \dfn{exception} events. Compiled \C{} code does not
Guido van Rossumdf804f81995-03-02 12:38:39 +0000523get interpreted, and hence is ``invisible'' to the profiler. All time
Fred Drake3a18f3b1998-04-02 19:36:25 +0000524spent in \C{} code (including built-in functions) will be charged to the
Fred Drake8fa5eb81998-02-27 05:23:37 +0000525Python function that invoked the \C{} code. If the \C{} code calls out
Guido van Rossumdf804f81995-03-02 12:38:39 +0000526to some native Python code, then those calls will be profiled
527properly.
528
529The second limitation has to do with accuracy of timing information.
530There is a fundamental problem with deterministic profilers involving
531accuracy. The most obvious restriction is that the underlying ``clock''
532is only ticking at a rate (typically) of about .001 seconds. Hence no
533measurements will be more accurate that that underlying clock. If
534enough measurements are taken, then the ``error'' will tend to average
535out. Unfortunately, removing this first error induces a second source
536of error...
537
538The second problem is that it ``takes a while'' from when an event is
539dispatched until the profiler's call to get the time actually
540\emph{gets} the state of the clock. Similarly, there is a certain lag
541when exiting the profiler event handler from the time that the clock's
542value was obtained (and then squirreled away), until the user's code
543is once again executing. As a result, functions that are called many
544times, or call many functions, will typically accumulate this error.
545The error that accumulates in this fashion is typically less than the
546accuracy of the clock (i.e., less than one clock tick), but it
547\emph{can} accumulate and become very significant. This profiler
548provides a means of calibrating itself for a given platform so that
549this error can be probabilistically (i.e., on the average) removed.
550After the profiler is calibrated, it will be more accurate (in a least
551square sense), but it will sometimes produce negative numbers (when
552call counts are exceptionally low, and the gods of probability work
553against you :-). ) Do \emph{NOT} be alarmed by negative numbers in
554the profile. They should \emph{only} appear if you have calibrated
555your profiler, and the results are actually better than without
556calibration.
557
558
559\section{Calibration}
560
561The profiler class has a hard coded constant that is added to each
562event handling time to compensate for the overhead of calling the time
563function, and socking away the results. The following procedure can
564be used to obtain this constant for a given platform (see discussion
565in section Limitations above).
566
Fred Drake19479911998-02-13 06:58:54 +0000567\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000568import profile
569pr = profile.Profile()
Guido van Rossum685ef4e1998-03-17 14:37:48 +0000570print pr.calibrate(100)
571print pr.calibrate(100)
572print pr.calibrate(100)
Fred Drake19479911998-02-13 06:58:54 +0000573\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000574
575The argument to \method{calibrate()} is the number of times to try to
576do the sample calls to get the CPU times. If your computer is
577\emph{very} fast, you might have to do:
Guido van Rossumdf804f81995-03-02 12:38:39 +0000578
Fred Drake19479911998-02-13 06:58:54 +0000579\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000580pr.calibrate(1000)
Fred Drake19479911998-02-13 06:58:54 +0000581\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000582
Guido van Rossumdf804f81995-03-02 12:38:39 +0000583or even:
584
Fred Drake19479911998-02-13 06:58:54 +0000585\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000586pr.calibrate(10000)
Fred Drake19479911998-02-13 06:58:54 +0000587\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000588
Guido van Rossumdf804f81995-03-02 12:38:39 +0000589The object of this exercise is to get a fairly consistent result.
590When you have a consistent answer, you are ready to use that number in
591the source code. For a Sun Sparcstation 1000 running Solaris 2.3, the
592magical number is about .00053. If you have a choice, you are better
593off with a smaller constant, and your results will ``less often'' show
594up as negative in profile statistics.
595
596The following shows how the trace_dispatch() method in the Profile
597class should be modified to install the calibration constant on a Sun
598Sparcstation 1000:
599
Fred Drake19479911998-02-13 06:58:54 +0000600\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000601def trace_dispatch(self, frame, event, arg):
602 t = self.timer()
603 t = t[0] + t[1] - self.t - .00053 # Calibration constant
604
605 if self.dispatch[event](frame,t):
Guido van Rossumdf804f81995-03-02 12:38:39 +0000606 t = self.timer()
Guido van Rossume47da0a1997-07-17 16:34:52 +0000607 self.t = t[0] + t[1]
608 else:
609 r = self.timer()
610 self.t = r[0] + r[1] - t # put back unrecorded delta
611 return
Fred Drake19479911998-02-13 06:58:54 +0000612\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000613
Guido van Rossumdf804f81995-03-02 12:38:39 +0000614Note that if there is no calibration constant, then the line
615containing the callibration constant should simply say:
616
Fred Drake19479911998-02-13 06:58:54 +0000617\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000618t = t[0] + t[1] - self.t # no calibration constant
Fred Drake19479911998-02-13 06:58:54 +0000619\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000620
Guido van Rossumdf804f81995-03-02 12:38:39 +0000621You can also achieve the same results using a derived class (and the
622profiler will actually run equally fast!!), but the above method is
623the simplest to use. I could have made the profiler ``self
624calibrating'', but it would have made the initialization of the
625profiler class slower, and would have required some \emph{very} fancy
626coding, or else the use of a variable where the constant \samp{.00053}
627was placed in the code shown. This is a \strong{VERY} critical
628performance section, and there is no reason to use a variable lookup
629at this point, when a constant can be used.
630
631
Guido van Rossum86cb0921995-03-20 12:59:56 +0000632\section{Extensions --- Deriving Better Profilers}
633\nodename{Profiler Extensions}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000634
Fred Drake8fa5eb81998-02-27 05:23:37 +0000635The \class{Profile} class of module \module{profile} was written so that
Guido van Rossumdf804f81995-03-02 12:38:39 +0000636derived classes could be developed to extend the profiler. Rather
637than describing all the details of such an effort, I'll just present
638the following two examples of derived classes that can be used to do
639profiling. If the reader is an avid Python programmer, then it should
640be possible to use these as a model and create similar (and perchance
641better) profile classes.
642
643If all you want to do is change how the timer is called, or which
644timer function is used, then the basic class has an option for that in
645the constructor for the class. Consider passing the name of a
646function to call into the constructor:
647
Fred Drake19479911998-02-13 06:58:54 +0000648\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000649pr = profile.Profile(your_time_func)
Fred Drake19479911998-02-13 06:58:54 +0000650\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000651
Guido van Rossumdf804f81995-03-02 12:38:39 +0000652The resulting profiler will call \code{your_time_func()} instead of
Fred Drake8fa5eb81998-02-27 05:23:37 +0000653\function{os.times()}. The function should return either a single number
654or a list of numbers (like what \function{os.times()} returns). If the
Guido van Rossumdf804f81995-03-02 12:38:39 +0000655function returns a single time number, or the list of returned numbers
656has length 2, then you will get an especially fast version of the
657dispatch routine.
658
659Be warned that you \emph{should} calibrate the profiler class for the
660timer function that you choose. For most machines, a timer that
661returns a lone integer value will provide the best results in terms of
Fred Drake8fa5eb81998-02-27 05:23:37 +0000662low overhead during profiling. (\function{os.times()} is
663\emph{pretty} bad, 'cause it returns a tuple of floating point values,
664so all arithmetic is floating point in the profiler!). If you want to
665substitute a better timer in the cleanest fashion, you should derive a
666class, and simply put in the replacement dispatch method that better
667handles your timer call, along with the appropriate calibration
668constant :-).
Guido van Rossumdf804f81995-03-02 12:38:39 +0000669
670
671\subsection{OldProfile Class}
672
673The following derived profiler simulates the old style profiler,
674providing errant results on recursive functions. The reason for the
675usefulness of this profiler is that it runs faster (i.e., less
676overhead) than the old profiler. It still creates all the caller
677stats, and is quite useful when there is \emph{no} recursion in the
678user's code. It is also a lot more accurate than the old profiler, as
679it does not charge all its overhead time to the user's code.
680
Fred Drake19479911998-02-13 06:58:54 +0000681\begin{verbatim}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000682class OldProfile(Profile):
683
684 def trace_dispatch_exception(self, frame, t):
685 rt, rtt, rct, rfn, rframe, rcur = self.cur
686 if rcur and not rframe is frame:
687 return self.trace_dispatch_return(rframe, t)
688 return 0
689
690 def trace_dispatch_call(self, frame, t):
691 fn = `frame.f_code`
692
693 self.cur = (t, 0, 0, fn, frame, self.cur)
694 if self.timings.has_key(fn):
695 tt, ct, callers = self.timings[fn]
696 self.timings[fn] = tt, ct, callers
697 else:
698 self.timings[fn] = 0, 0, {}
699 return 1
700
701 def trace_dispatch_return(self, frame, t):
702 rt, rtt, rct, rfn, frame, rcur = self.cur
703 rtt = rtt + t
704 sft = rtt + rct
705
706 pt, ptt, pct, pfn, pframe, pcur = rcur
707 self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur
708
709 tt, ct, callers = self.timings[rfn]
710 if callers.has_key(pfn):
711 callers[pfn] = callers[pfn] + 1
712 else:
713 callers[pfn] = 1
714 self.timings[rfn] = tt+rtt, ct + sft, callers
715
716 return 1
717
718
719 def snapshot_stats(self):
720 self.stats = {}
721 for func in self.timings.keys():
722 tt, ct, callers = self.timings[func]
723 nor_func = self.func_normalize(func)
724 nor_callers = {}
725 nc = 0
726 for func_caller in callers.keys():
Fred Drake5dabeed1998-04-03 07:02:35 +0000727 nor_callers[self.func_normalize(func_caller)] = \
728 callers[func_caller]
Guido van Rossumdf804f81995-03-02 12:38:39 +0000729 nc = nc + callers[func_caller]
730 self.stats[nor_func] = nc, nc, tt, ct, nor_callers
Fred Drake19479911998-02-13 06:58:54 +0000731\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000732
Guido van Rossumdf804f81995-03-02 12:38:39 +0000733\subsection{HotProfile Class}
734
735This profiler is the fastest derived profile example. It does not
736calculate caller-callee relationships, and does not calculate
737cumulative time under a function. It only calculates time spent in a
738function, so it runs very quickly (re: very low overhead). In truth,
739the basic profiler is so fast, that is probably not worth the savings
740to give up the data, but this class still provides a nice example.
741
Fred Drake19479911998-02-13 06:58:54 +0000742\begin{verbatim}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000743class HotProfile(Profile):
744
745 def trace_dispatch_exception(self, frame, t):
746 rt, rtt, rfn, rframe, rcur = self.cur
747 if rcur and not rframe is frame:
748 return self.trace_dispatch_return(rframe, t)
749 return 0
750
751 def trace_dispatch_call(self, frame, t):
752 self.cur = (t, 0, frame, self.cur)
753 return 1
754
755 def trace_dispatch_return(self, frame, t):
756 rt, rtt, frame, rcur = self.cur
757
758 rfn = `frame.f_code`
759
760 pt, ptt, pframe, pcur = rcur
761 self.cur = pt, ptt+rt, pframe, pcur
762
763 if self.timings.has_key(rfn):
764 nc, tt = self.timings[rfn]
765 self.timings[rfn] = nc + 1, rt + rtt + tt
766 else:
767 self.timings[rfn] = 1, rt + rtt
768
769 return 1
770
771
772 def snapshot_stats(self):
773 self.stats = {}
774 for func in self.timings.keys():
775 nc, tt = self.timings[func]
776 nor_func = self.func_normalize(func)
777 self.stats[nor_func] = nc, nc, tt, 0, {}
Fred Drake19479911998-02-13 06:58:54 +0000778\end{verbatim}