blob: 47ff39495f916845a72fa9360b241086c09d5b05 [file] [log] [blame]
Fred Drakeea003fc1999-04-05 21:59:15 +00001\chapter{The Python Profiler \label{profile}}
2
3\sectionauthor{James Roskind}{}
Guido van Rossumdf804f81995-03-02 12:38:39 +00004
Fred Drake4b3f0311996-12-13 22:04:31 +00005Copyright \copyright{} 1994, by InfoSeek Corporation, all rights reserved.
Fred Drake5dabeed1998-04-03 07:02:35 +00006\index{InfoSeek Corporation}
Guido van Rossumdf804f81995-03-02 12:38:39 +00007
Fred Drakeea003fc1999-04-05 21:59:15 +00008Written by James Roskind.\footnote{
9 Updated and converted to \LaTeX\ by Guido van Rossum. The references to
10 the old profiler are left in the text, although it no longer exists.}
Guido van Rossumdf804f81995-03-02 12:38:39 +000011
12Permission to use, copy, modify, and distribute this Python software
13and its associated documentation for any purpose (subject to the
14restriction in the following sentence) without fee is hereby granted,
15provided that the above copyright notice appears in all copies, and
16that both that copyright notice and this permission notice appear in
17supporting documentation, and that the name of InfoSeek not be used in
18advertising or publicity pertaining to distribution of the software
19without specific, written prior permission. This permission is
20explicitly restricted to the copying and modification of the software
21to remain in Python, compiled Python, or other languages (such as C)
22wherein the modified or derived code is exclusively imported into a
23Python module.
24
25INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
26SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
27FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION BE LIABLE FOR ANY
28SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
29RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
30CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
31CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
32
33
34The profiler was written after only programming in Python for 3 weeks.
35As a result, it is probably clumsy code, but I don't know for sure yet
36'cause I'm a beginner :-). I did work hard to make the code run fast,
37so that profiling would be a reasonable thing to do. I tried not to
38repeat code fragments, but I'm sure I did some stuff in really awkward
39ways at times. Please send suggestions for improvements to:
Fred Drake8fa5eb81998-02-27 05:23:37 +000040\email{jar@netscape.com}. I won't promise \emph{any} support. ...but
Guido van Rossumdf804f81995-03-02 12:38:39 +000041I'd appreciate the feedback.
42
43
Guido van Rossum470be141995-03-17 16:07:09 +000044\section{Introduction to the profiler}
Guido van Rossum86cb0921995-03-20 12:59:56 +000045\nodename{Profiler Introduction}
Guido van Rossumdf804f81995-03-02 12:38:39 +000046
47A \dfn{profiler} is a program that describes the run time performance
48of a program, providing a variety of statistics. This documentation
49describes the profiler functionality provided in the modules
Fred Drake8fa5eb81998-02-27 05:23:37 +000050\module{profile} and \module{pstats}. This profiler provides
Guido van Rossumdf804f81995-03-02 12:38:39 +000051\dfn{deterministic profiling} of any Python programs. It also
52provides a series of report generation tools to allow users to rapidly
53examine the results of a profile operation.
Fred Drake8fa5eb81998-02-27 05:23:37 +000054\index{deterministic profiling}
55\index{profiling, deterministic}
Guido van Rossumdf804f81995-03-02 12:38:39 +000056
57
58\section{How Is This Profiler Different From The Old Profiler?}
Guido van Rossum86cb0921995-03-20 12:59:56 +000059\nodename{Profiler Changes}
Guido van Rossumdf804f81995-03-02 12:38:39 +000060
Guido van Rossum364e6431997-11-18 15:28:46 +000061(This section is of historical importance only; the old profiler
62discussed here was last seen in Python 1.1.)
63
Guido van Rossumdf804f81995-03-02 12:38:39 +000064The big changes from old profiling module are that you get more
65information, and you pay less CPU time. It's not a trade-off, it's a
66trade-up.
67
68To be specific:
69
70\begin{description}
71
72\item[Bugs removed:]
73Local stack frame is no longer molested, execution time is now charged
74to correct functions.
75
76\item[Accuracy increased:]
77Profiler execution time is no longer charged to user's code,
78calibration for platform is supported, file reads are not done \emph{by}
79profiler \emph{during} profiling (and charged to user's code!).
80
81\item[Speed increased:]
82Overhead CPU cost was reduced by more than a factor of two (perhaps a
83factor of five), lightweight profiler module is all that must be
Fred Drake8fa5eb81998-02-27 05:23:37 +000084loaded, and the report generating module (\module{pstats}) is not needed
Guido van Rossumdf804f81995-03-02 12:38:39 +000085during profiling.
86
87\item[Recursive functions support:]
88Cumulative times in recursive functions are correctly calculated;
89recursive entries are counted.
90
91\item[Large growth in report generating UI:]
92Distinct profiles runs can be added together forming a comprehensive
93report; functions that import statistics take arbitrary lists of
94files; sorting criteria is now based on keywords (instead of 4 integer
95options); reports shows what functions were profiled as well as what
96profile file was referenced; output format has been improved.
97
98\end{description}
99
100
101\section{Instant Users Manual}
102
103This section is provided for users that ``don't want to read the
104manual.'' It provides a very brief overview, and allows a user to
105rapidly perform profiling on an existing application.
106
107To profile an application with a main entry point of \samp{foo()}, you
108would add the following to your module:
109
Fred Drake19479911998-02-13 06:58:54 +0000110\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000111import profile
Fred Drake2cb824c1998-04-09 18:10:35 +0000112profile.run('foo()')
Fred Drake19479911998-02-13 06:58:54 +0000113\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000114%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000115The above action would cause \samp{foo()} to be run, and a series of
116informative lines (the profile) to be printed. The above approach is
117most useful when working with the interpreter. If you would like to
118save the results of a profile into a file for later examination, you
Fred Drake8fa5eb81998-02-27 05:23:37 +0000119can supply a file name as the second argument to the \function{run()}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000120function:
121
Fred Drake19479911998-02-13 06:58:54 +0000122\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000123import profile
Fred Drake2cb824c1998-04-09 18:10:35 +0000124profile.run('foo()', 'fooprof')
Fred Drake19479911998-02-13 06:58:54 +0000125\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000126%
Fred Drake8fa5eb81998-02-27 05:23:37 +0000127The file \file{profile.py} can also be invoked as
Guido van Rossumbac80021997-06-02 17:29:12 +0000128a script to profile another script. For example:
Fred Drake8fa5eb81998-02-27 05:23:37 +0000129
130\begin{verbatim}
Fred Drake5dabeed1998-04-03 07:02:35 +0000131python /usr/local/lib/python1.5/profile.py myscript.py
Fred Drake8fa5eb81998-02-27 05:23:37 +0000132\end{verbatim}
Guido van Rossumbac80021997-06-02 17:29:12 +0000133
Guido van Rossumdf804f81995-03-02 12:38:39 +0000134When you wish to review the profile, you should use the methods in the
Fred Drake8fa5eb81998-02-27 05:23:37 +0000135\module{pstats} module. Typically you would load the statistics data as
Guido van Rossumdf804f81995-03-02 12:38:39 +0000136follows:
137
Fred Drake19479911998-02-13 06:58:54 +0000138\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000139import pstats
140p = pstats.Stats('fooprof')
Fred Drake19479911998-02-13 06:58:54 +0000141\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000142%
Fred Drake8fa5eb81998-02-27 05:23:37 +0000143The class \class{Stats} (the above code just created an instance of
Guido van Rossumdf804f81995-03-02 12:38:39 +0000144this class) has a variety of methods for manipulating and printing the
145data that was just read into \samp{p}. When you ran
Fred Drake8fa5eb81998-02-27 05:23:37 +0000146\function{profile.run()} above, what was printed was the result of three
Guido van Rossumdf804f81995-03-02 12:38:39 +0000147method calls:
148
Fred Drake19479911998-02-13 06:58:54 +0000149\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000150p.strip_dirs().sort_stats(-1).print_stats()
Fred Drake19479911998-02-13 06:58:54 +0000151\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000152%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000153The first method removed the extraneous path from all the module
154names. The second method sorted all the entries according to the
155standard module/line/name string that is printed (this is to comply
156with the semantics of the old profiler). The third method printed out
157all the statistics. You might try the following sort calls:
158
Fred Drake19479911998-02-13 06:58:54 +0000159\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000160p.sort_stats('name')
161p.print_stats()
Fred Drake19479911998-02-13 06:58:54 +0000162\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000163%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000164The first call will actually sort the list by function name, and the
165second call will print out the statistics. The following are some
166interesting calls to experiment with:
167
Fred Drake19479911998-02-13 06:58:54 +0000168\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000169p.sort_stats('cumulative').print_stats(10)
Fred Drake19479911998-02-13 06:58:54 +0000170\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000171%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000172This sorts the profile by cumulative time in a function, and then only
173prints the ten most significant lines. If you want to understand what
174algorithms are taking time, the above line is what you would use.
175
176If you were looking to see what functions were looping a lot, and
177taking a lot of time, you would do:
178
Fred Drake19479911998-02-13 06:58:54 +0000179\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000180p.sort_stats('time').print_stats(10)
Fred Drake19479911998-02-13 06:58:54 +0000181\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000182%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000183to sort according to time spent within each function, and then print
184the statistics for the top ten functions.
185
186You might also try:
187
Fred Drake19479911998-02-13 06:58:54 +0000188\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000189p.sort_stats('file').print_stats('__init__')
Fred Drake19479911998-02-13 06:58:54 +0000190\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000191%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000192This will sort all the statistics by file name, and then print out
193statistics for only the class init methods ('cause they are spelled
Fred Drake8fa5eb81998-02-27 05:23:37 +0000194with \samp{__init__} in them). As one final example, you could try:
Guido van Rossumdf804f81995-03-02 12:38:39 +0000195
Fred Drake19479911998-02-13 06:58:54 +0000196\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000197p.sort_stats('time', 'cum').print_stats(.5, 'init')
Fred Drake19479911998-02-13 06:58:54 +0000198\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000199%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000200This line sorts statistics with a primary key of time, and a secondary
201key of cumulative time, and then prints out some of the statistics.
202To be specific, the list is first culled down to 50\% (re: \samp{.5})
203of its original size, then only lines containing \code{init} are
204maintained, and that sub-sub-list is printed.
205
206If you wondered what functions called the above functions, you could
207now (\samp{p} is still sorted according to the last criteria) do:
208
Fred Drake19479911998-02-13 06:58:54 +0000209\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000210p.print_callers(.5, 'init')
Fred Drake19479911998-02-13 06:58:54 +0000211\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000212
Guido van Rossumdf804f81995-03-02 12:38:39 +0000213and you would get a list of callers for each of the listed functions.
214
215If you want more functionality, you're going to have to read the
216manual, or guess what the following functions do:
217
Fred Drake19479911998-02-13 06:58:54 +0000218\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000219p.print_callees()
220p.add('fooprof')
Fred Drake19479911998-02-13 06:58:54 +0000221\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000222%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000223\section{What Is Deterministic Profiling?}
Guido van Rossum86cb0921995-03-20 12:59:56 +0000224\nodename{Deterministic Profiling}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000225
226\dfn{Deterministic profiling} is meant to reflect the fact that all
227\dfn{function call}, \dfn{function return}, and \dfn{exception} events
228are monitored, and precise timings are made for the intervals between
229these events (during which time the user's code is executing). In
230contrast, \dfn{statistical profiling} (which is not done by this
231module) randomly samples the effective instruction pointer, and
232deduces where time is being spent. The latter technique traditionally
233involves less overhead (as the code does not need to be instrumented),
234but provides only relative indications of where time is being spent.
235
236In Python, since there is an interpreter active during execution, the
237presence of instrumented code is not required to do deterministic
238profiling. Python automatically provides a \dfn{hook} (optional
239callback) for each event. In addition, the interpreted nature of
240Python tends to add so much overhead to execution, that deterministic
241profiling tends to only add small processing overhead in typical
242applications. The result is that deterministic profiling is not that
243expensive, yet provides extensive run time statistics about the
244execution of a Python program.
245
246Call count statistics can be used to identify bugs in code (surprising
247counts), and to identify possible inline-expansion points (high call
248counts). Internal time statistics can be used to identify ``hot
249loops'' that should be carefully optimized. Cumulative time
250statistics should be used to identify high level errors in the
251selection of algorithms. Note that the unusual handling of cumulative
252times in this profiler allows statistics for recursive implementations
253of algorithms to be directly compared to iterative implementations.
254
255
256\section{Reference Manual}
Fred Drakeb91e9341998-07-23 17:59:49 +0000257\declaremodule{standard}{profile}
258
259\modulesynopsis{None}
260
Guido van Rossumdf804f81995-03-02 12:38:39 +0000261
Guido van Rossumdf804f81995-03-02 12:38:39 +0000262
263The primary entry point for the profiler is the global function
Fred Drake8fa5eb81998-02-27 05:23:37 +0000264\function{profile.run()}. It is typically used to create any profile
Guido van Rossumdf804f81995-03-02 12:38:39 +0000265information. The reports are formatted and printed using methods of
Fred Drake8fa5eb81998-02-27 05:23:37 +0000266the class \class{pstats.Stats}. The following is a description of all
Guido van Rossumdf804f81995-03-02 12:38:39 +0000267of these standard entry points and functions. For a more in-depth
268view of some of the code, consider reading the later section on
269Profiler Extensions, which includes discussion of how to derive
270``better'' profilers from the classes presented, or reading the source
271code for these modules.
272
Fred Drake8fe533e1998-03-27 05:27:08 +0000273\begin{funcdesc}{run}{string\optional{, filename\optional{, ...}}}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000274
275This function takes a single argument that has can be passed to the
Fred Drake8fa5eb81998-02-27 05:23:37 +0000276\keyword{exec} statement, and an optional file name. In all cases this
277routine attempts to \keyword{exec} its first argument, and gather profiling
Guido van Rossumdf804f81995-03-02 12:38:39 +0000278statistics from the execution. If no file name is present, then this
279function automatically prints a simple profiling report, sorted by the
280standard name string (file/line/function-name) that is presented in
281each line. The following is a typical output from such a call:
282
Fred Drake19479911998-02-13 06:58:54 +0000283\begin{verbatim}
Guido van Rossum96628a91995-04-10 11:34:00 +0000284 main()
285 2706 function calls (2004 primitive calls) in 4.504 CPU seconds
Guido van Rossumdf804f81995-03-02 12:38:39 +0000286
Guido van Rossum96628a91995-04-10 11:34:00 +0000287Ordered by: standard name
Guido van Rossumdf804f81995-03-02 12:38:39 +0000288
Guido van Rossum96628a91995-04-10 11:34:00 +0000289ncalls tottime percall cumtime percall filename:lineno(function)
290 2 0.006 0.003 0.953 0.477 pobject.py:75(save_objects)
291 43/3 0.533 0.012 0.749 0.250 pobject.py:99(evaluate)
292 ...
Fred Drake19479911998-02-13 06:58:54 +0000293\end{verbatim}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000294
295The first line indicates that this profile was generated by the call:\\
296\code{profile.run('main()')}, and hence the exec'ed string is
297\code{'main()'}. The second line indicates that 2706 calls were
298monitored. Of those calls, 2004 were \dfn{primitive}. We define
299\dfn{primitive} to mean that the call was not induced via recursion.
300The next line: \code{Ordered by:\ standard name}, indicates that
301the text string in the far right column was used to sort the output.
302The column headings include:
303
304\begin{description}
305
306\item[ncalls ]
307for the number of calls,
308
309\item[tottime ]
310for the total time spent in the given function (and excluding time
311made in calls to sub-functions),
312
313\item[percall ]
314is the quotient of \code{tottime} divided by \code{ncalls}
315
316\item[cumtime ]
317is the total time spent in this and all subfunctions (i.e., from
318invocation till exit). This figure is accurate \emph{even} for recursive
319functions.
320
321\item[percall ]
322is the quotient of \code{cumtime} divided by primitive calls
323
324\item[filename:lineno(function) ]
325provides the respective data of each function
326
327\end{description}
328
329When there are two numbers in the first column (e.g.: \samp{43/3}),
330then the latter is the number of primitive calls, and the former is
331the actual number of calls. Note that when the function does not
332recurse, these two values are the same, and only the single figure is
333printed.
Guido van Rossum96628a91995-04-10 11:34:00 +0000334
Guido van Rossumdf804f81995-03-02 12:38:39 +0000335\end{funcdesc}
336
Fred Drake8fa5eb81998-02-27 05:23:37 +0000337Analysis of the profiler data is done using this class from the
338\module{pstats} module:
339
Fred Drake8fe533e1998-03-27 05:27:08 +0000340% now switch modules....
341\stmodindex{pstats}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000342
Fred Drakecce10901998-03-17 06:33:25 +0000343\begin{classdesc}{Stats}{filename\optional{, ...}}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000344This class constructor creates an instance of a ``statistics object''
Fred Drake8fa5eb81998-02-27 05:23:37 +0000345from a \var{filename} (or set of filenames). \class{Stats} objects are
Guido van Rossumdf804f81995-03-02 12:38:39 +0000346manipulated by methods, in order to print useful reports.
347
348The file selected by the above constructor must have been created by
Fred Drake8fa5eb81998-02-27 05:23:37 +0000349the corresponding version of \module{profile}. To be specific, there is
350\emph{no} file compatibility guaranteed with future versions of this
Guido van Rossumdf804f81995-03-02 12:38:39 +0000351profiler, and there is no compatibility with files produced by other
352profilers (e.g., the old system profiler).
353
354If several files are provided, all the statistics for identical
355functions will be coalesced, so that an overall view of several
356processes can be considered in a single report. If additional files
Fred Drake8fa5eb81998-02-27 05:23:37 +0000357need to be combined with data in an existing \class{Stats} object, the
358\method{add()} method can be used.
359\end{classdesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000360
361
Fred Drake3a0351c1998-04-04 07:23:21 +0000362\subsection{The \module{Stats} Class}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000363
Fred Drake19479911998-02-13 06:58:54 +0000364\setindexsubitem{(Stats method)}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000365
Fred Drake8fe533e1998-03-27 05:27:08 +0000366\begin{methoddesc}{strip_dirs}{}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000367This method for the \class{Stats} class removes all leading path
368information from file names. It is very useful in reducing the size
369of the printout to fit within (close to) 80 columns. This method
370modifies the object, and the stripped information is lost. After
371performing a strip operation, the object is considered to have its
372entries in a ``random'' order, as it was just after object
373initialization and loading. If \method{strip_dirs()} causes two
374function names to be indistinguishable (i.e., they are on the same
375line of the same filename, and have the same function name), then the
376statistics for these two entries are accumulated into a single entry.
Fred Drake8fe533e1998-03-27 05:27:08 +0000377\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000378
379
Fred Drake8fe533e1998-03-27 05:27:08 +0000380\begin{methoddesc}{add}{filename\optional{, ...}}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000381This method of the \class{Stats} class accumulates additional
382profiling information into the current profiling object. Its
383arguments should refer to filenames created by the corresponding
384version of \function{profile.run()}. Statistics for identically named
385(re: file, line, name) functions are automatically accumulated into
386single function statistics.
Fred Drake8fe533e1998-03-27 05:27:08 +0000387\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000388
Fred Drake8fe533e1998-03-27 05:27:08 +0000389\begin{methoddesc}{sort_stats}{key\optional{, ...}}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000390This method modifies the \class{Stats} object by sorting it according
391to the supplied criteria. The argument is typically a string
Fred Drake2cb824c1998-04-09 18:10:35 +0000392identifying the basis of a sort (example: \code{'time'} or
393\code{'name'}).
Guido van Rossumdf804f81995-03-02 12:38:39 +0000394
395When more than one key is provided, then additional keys are used as
396secondary criteria when the there is equality in all keys selected
Fred Drake8fa5eb81998-02-27 05:23:37 +0000397before them. For example, \samp{sort_stats('name', 'file')} will sort
398all the entries according to their function name, and resolve all ties
Guido van Rossumdf804f81995-03-02 12:38:39 +0000399(identical function names) by sorting by file name.
400
401Abbreviations can be used for any key names, as long as the
402abbreviation is unambiguous. The following are the keys currently
403defined:
404
Fred Drakeee601911998-04-11 20:53:03 +0000405\begin{tableii}{l|l}{code}{Valid Arg}{Meaning}
Fred Drake5dabeed1998-04-03 07:02:35 +0000406 \lineii{'calls'}{call count}
407 \lineii{'cumulative'}{cumulative time}
408 \lineii{'file'}{file name}
409 \lineii{'module'}{file name}
410 \lineii{'pcalls'}{primitive call count}
411 \lineii{'line'}{line number}
412 \lineii{'name'}{function name}
413 \lineii{'nfl'}{name/file/line}
414 \lineii{'stdname'}{standard name}
415 \lineii{'time'}{internal time}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000416\end{tableii}
417
418Note that all sorts on statistics are in descending order (placing
419most time consuming items first), where as name, file, and line number
420searches are in ascending order (i.e., alphabetical). The subtle
Fred Drake2cb824c1998-04-09 18:10:35 +0000421distinction between \code{'nfl'} and \code{'stdname'} is that the
Guido van Rossumdf804f81995-03-02 12:38:39 +0000422standard name is a sort of the name as printed, which means that the
423embedded line numbers get compared in an odd way. For example, lines
4243, 20, and 40 would (if the file names were the same) appear in the
Fred Drake2cb824c1998-04-09 18:10:35 +0000425string order 20, 3 and 40. In contrast, \code{'nfl'} does a numeric
426compare of the line numbers. In fact, \code{sort_stats('nfl')} is the
427same as \code{sort_stats('name', 'file', 'line')}.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000428
429For compatibility with the old profiler, the numeric arguments
Fred Drake2cb824c1998-04-09 18:10:35 +0000430\code{-1}, \code{0}, \code{1}, and \code{2} are permitted. They are
431interpreted as \code{'stdname'}, \code{'calls'}, \code{'time'}, and
432\code{'cumulative'} respectively. If this old style format (numeric)
Guido van Rossumdf804f81995-03-02 12:38:39 +0000433is used, only one sort key (the numeric key) will be used, and
434additional arguments will be silently ignored.
Fred Drake8fe533e1998-03-27 05:27:08 +0000435\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000436
437
Fred Drake8fe533e1998-03-27 05:27:08 +0000438\begin{methoddesc}{reverse_order}{}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000439This method for the \class{Stats} class reverses the ordering of the basic
Guido van Rossumdf804f81995-03-02 12:38:39 +0000440list within the object. This method is provided primarily for
441compatibility with the old profiler. Its utility is questionable
442now that ascending vs descending order is properly selected based on
443the sort key of choice.
Fred Drake8fe533e1998-03-27 05:27:08 +0000444\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000445
Fred Drake8fe533e1998-03-27 05:27:08 +0000446\begin{methoddesc}{print_stats}{restriction\optional{, ...}}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000447This method for the \class{Stats} class prints out a report as described
448in the \function{profile.run()} definition.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000449
Fred Drake8fa5eb81998-02-27 05:23:37 +0000450The order of the printing is based on the last \method{sort_stats()}
451operation done on the object (subject to caveats in \method{add()} and
452\method{strip_dirs()}.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000453
454The arguments provided (if any) can be used to limit the list down to
455the significant entries. Initially, the list is taken to be the
456complete set of profiled functions. Each restriction is either an
457integer (to select a count of lines), or a decimal fraction between
4580.0 and 1.0 inclusive (to select a percentage of lines), or a regular
Guido van Rossum364e6431997-11-18 15:28:46 +0000459expression (to pattern match the standard name that is printed; as of
460Python 1.5b1, this uses the Perl-style regular expression syntax
Fred Drake8fa5eb81998-02-27 05:23:37 +0000461defined by the \module{re} module). If several restrictions are
Guido van Rossum364e6431997-11-18 15:28:46 +0000462provided, then they are applied sequentially. For example:
Guido van Rossumdf804f81995-03-02 12:38:39 +0000463
Fred Drake19479911998-02-13 06:58:54 +0000464\begin{verbatim}
Fred Drake2cb824c1998-04-09 18:10:35 +0000465print_stats(.1, 'foo:')
Fred Drake19479911998-02-13 06:58:54 +0000466\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000467
Guido van Rossumdf804f81995-03-02 12:38:39 +0000468would first limit the printing to first 10\% of list, and then only
469print functions that were part of filename \samp{.*foo:}. In
470contrast, the command:
471
Fred Drake19479911998-02-13 06:58:54 +0000472\begin{verbatim}
Fred Drake2cb824c1998-04-09 18:10:35 +0000473print_stats('foo:', .1)
Fred Drake19479911998-02-13 06:58:54 +0000474\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000475
Guido van Rossumdf804f81995-03-02 12:38:39 +0000476would limit the list to all functions having file names \samp{.*foo:},
477and then proceed to only print the first 10\% of them.
Fred Drake8fe533e1998-03-27 05:27:08 +0000478\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000479
480
Fred Drake8fe533e1998-03-27 05:27:08 +0000481\begin{methoddesc}{print_callers}{restrictions\optional{, ...}}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000482This method for the \class{Stats} class prints a list of all functions
Guido van Rossumdf804f81995-03-02 12:38:39 +0000483that called each function in the profiled database. The ordering is
Fred Drake8fa5eb81998-02-27 05:23:37 +0000484identical to that provided by \method{print_stats()}, and the definition
Guido van Rossumdf804f81995-03-02 12:38:39 +0000485of the restricting argument is also identical. For convenience, a
486number is shown in parentheses after each caller to show how many
487times this specific call was made. A second non-parenthesized number
488is the cumulative time spent in the function at the right.
Fred Drake8fe533e1998-03-27 05:27:08 +0000489\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000490
Fred Drake8fe533e1998-03-27 05:27:08 +0000491\begin{methoddesc}{print_callees}{restrictions\optional{, ...}}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000492This method for the \class{Stats} class prints a list of all function
Guido van Rossumdf804f81995-03-02 12:38:39 +0000493that were called by the indicated function. Aside from this reversal
494of direction of calls (re: called vs was called by), the arguments and
Fred Drake8fa5eb81998-02-27 05:23:37 +0000495ordering are identical to the \method{print_callers()} method.
Fred Drake8fe533e1998-03-27 05:27:08 +0000496\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000497
Fred Drake8fe533e1998-03-27 05:27:08 +0000498\begin{methoddesc}{ignore}{}
Fred Drakeea003fc1999-04-05 21:59:15 +0000499\deprecated{1.5.1}{This is not needed in modern versions of
500Python.\footnote{
501 This was once necessary, when Python would print any unused expression
502 result that was not \code{None}. The method is still defined for
503 backward compatibility.}}
Fred Drake8fe533e1998-03-27 05:27:08 +0000504\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000505
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},
Fred Drake8fa5eb81998-02-27 05:23:37 +0000511\dfn{return}, and \dfn{exception} events. Compiled \C{} code does not
Guido van Rossumdf804f81995-03-02 12:38:39 +0000512get interpreted, and hence is ``invisible'' to the profiler. All time
Fred Drake3a18f3b1998-04-02 19:36:25 +0000513spent in \C{} code (including built-in functions) will be charged to the
Fred Drake8fa5eb81998-02-27 05:23:37 +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
Fred Drake19479911998-02-13 06:58:54 +0000556\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000557import profile
558pr = profile.Profile()
Guido van Rossum685ef4e1998-03-17 14:37:48 +0000559print pr.calibrate(100)
560print pr.calibrate(100)
561print pr.calibrate(100)
Fred Drake19479911998-02-13 06:58:54 +0000562\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000563
564The argument to \method{calibrate()} is the number of times to try to
565do the sample calls to get the CPU times. If your computer is
566\emph{very} fast, you might have to do:
Guido van Rossumdf804f81995-03-02 12:38:39 +0000567
Fred Drake19479911998-02-13 06:58:54 +0000568\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000569pr.calibrate(1000)
Fred Drake19479911998-02-13 06:58:54 +0000570\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000571
Guido van Rossumdf804f81995-03-02 12:38:39 +0000572or even:
573
Fred Drake19479911998-02-13 06:58:54 +0000574\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000575pr.calibrate(10000)
Fred Drake19479911998-02-13 06:58:54 +0000576\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000577
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
Fred Drake19479911998-02-13 06:58:54 +0000589\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000590def 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
Fred Drake19479911998-02-13 06:58:54 +0000601\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000602
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
Fred Drake19479911998-02-13 06:58:54 +0000606\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000607t = t[0] + t[1] - self.t # no calibration constant
Fred Drake19479911998-02-13 06:58:54 +0000608\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000609
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
Fred Drake8fa5eb81998-02-27 05:23:37 +0000624The \class{Profile} class of module \module{profile} was written so that
Guido van Rossumdf804f81995-03-02 12:38:39 +0000625derived 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
Fred Drake19479911998-02-13 06:58:54 +0000637\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000638pr = profile.Profile(your_time_func)
Fred Drake19479911998-02-13 06:58:54 +0000639\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000640
Guido van Rossumdf804f81995-03-02 12:38:39 +0000641The resulting profiler will call \code{your_time_func()} instead of
Fred Drake8fa5eb81998-02-27 05:23:37 +0000642\function{os.times()}. The function should return either a single number
643or a list of numbers (like what \function{os.times()} returns). If the
Guido van Rossumdf804f81995-03-02 12:38:39 +0000644function 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
Fred Drake8fa5eb81998-02-27 05:23:37 +0000651low overhead during profiling. (\function{os.times()} is
652\emph{pretty} bad, 'cause it returns a tuple of floating point values,
653so all arithmetic is floating point in the profiler!). If you want to
654substitute a better timer in the cleanest fashion, you should derive a
655class, and simply put in the replacement dispatch method that better
656handles your timer call, along with the appropriate calibration
657constant :-).
Guido van Rossumdf804f81995-03-02 12:38:39 +0000658
659
660\subsection{OldProfile Class}
661
662The following derived profiler simulates the old style profiler,
663providing errant results on recursive functions. The reason for the
664usefulness of this profiler is that it runs faster (i.e., less
665overhead) than the old profiler. It still creates all the caller
666stats, and is quite useful when there is \emph{no} recursion in the
667user's code. It is also a lot more accurate than the old profiler, as
668it does not charge all its overhead time to the user's code.
669
Fred Drake19479911998-02-13 06:58:54 +0000670\begin{verbatim}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000671class OldProfile(Profile):
672
673 def trace_dispatch_exception(self, frame, t):
674 rt, rtt, rct, rfn, rframe, rcur = self.cur
675 if rcur and not rframe is frame:
676 return self.trace_dispatch_return(rframe, t)
677 return 0
678
679 def trace_dispatch_call(self, frame, t):
680 fn = `frame.f_code`
681
682 self.cur = (t, 0, 0, fn, frame, self.cur)
683 if self.timings.has_key(fn):
684 tt, ct, callers = self.timings[fn]
685 self.timings[fn] = tt, ct, callers
686 else:
687 self.timings[fn] = 0, 0, {}
688 return 1
689
690 def trace_dispatch_return(self, frame, t):
691 rt, rtt, rct, rfn, frame, rcur = self.cur
692 rtt = rtt + t
693 sft = rtt + rct
694
695 pt, ptt, pct, pfn, pframe, pcur = rcur
696 self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur
697
698 tt, ct, callers = self.timings[rfn]
699 if callers.has_key(pfn):
700 callers[pfn] = callers[pfn] + 1
701 else:
702 callers[pfn] = 1
703 self.timings[rfn] = tt+rtt, ct + sft, callers
704
705 return 1
706
707
708 def snapshot_stats(self):
709 self.stats = {}
710 for func in self.timings.keys():
711 tt, ct, callers = self.timings[func]
712 nor_func = self.func_normalize(func)
713 nor_callers = {}
714 nc = 0
715 for func_caller in callers.keys():
Fred Drake5dabeed1998-04-03 07:02:35 +0000716 nor_callers[self.func_normalize(func_caller)] = \
717 callers[func_caller]
Guido van Rossumdf804f81995-03-02 12:38:39 +0000718 nc = nc + callers[func_caller]
719 self.stats[nor_func] = nc, nc, tt, ct, nor_callers
Fred Drake19479911998-02-13 06:58:54 +0000720\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000721
Guido van Rossumdf804f81995-03-02 12:38:39 +0000722\subsection{HotProfile Class}
723
724This profiler is the fastest derived profile example. It does not
725calculate caller-callee relationships, and does not calculate
726cumulative time under a function. It only calculates time spent in a
727function, so it runs very quickly (re: very low overhead). In truth,
728the basic profiler is so fast, that is probably not worth the savings
729to give up the data, but this class still provides a nice example.
730
Fred Drake19479911998-02-13 06:58:54 +0000731\begin{verbatim}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000732class HotProfile(Profile):
733
734 def trace_dispatch_exception(self, frame, t):
735 rt, rtt, rfn, rframe, rcur = self.cur
736 if rcur and not rframe is frame:
737 return self.trace_dispatch_return(rframe, t)
738 return 0
739
740 def trace_dispatch_call(self, frame, t):
741 self.cur = (t, 0, frame, self.cur)
742 return 1
743
744 def trace_dispatch_return(self, frame, t):
745 rt, rtt, frame, rcur = self.cur
746
747 rfn = `frame.f_code`
748
749 pt, ptt, pframe, pcur = rcur
750 self.cur = pt, ptt+rt, pframe, pcur
751
752 if self.timings.has_key(rfn):
753 nc, tt = self.timings[rfn]
754 self.timings[rfn] = nc + 1, rt + rtt + tt
755 else:
756 self.timings[rfn] = 1, rt + rtt
757
758 return 1
759
760
761 def snapshot_stats(self):
762 self.stats = {}
763 for func in self.timings.keys():
764 nc, tt = self.timings[func]
765 nor_func = self.func_normalize(func)
766 self.stats[nor_func] = nc, nc, tt, 0, {}
Fred Drake19479911998-02-13 06:58:54 +0000767\end{verbatim}