blob: 2e3bc3dd5648ce49efebe357d355e5295e43da45 [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\stmodindex{profile}
4\stmodindex{pstats}
5
Fred Drake4b3f0311996-12-13 22:04:31 +00006Copyright \copyright{} 1994, by InfoSeek Corporation, all rights reserved.
Guido van Rossumdf804f81995-03-02 12:38:39 +00007
8Written by James Roskind%
9\footnote{
Guido van Rossum6c4f0031995-03-07 10:14:09 +000010Updated and converted to \LaTeX\ by Guido van Rossum. The references to
Guido van Rossumdf804f81995-03-02 12:38:39 +000011the old profiler are left in the text, although it no longer exists.
12}
13
14Permission to use, copy, modify, and distribute this Python software
15and its associated documentation for any purpose (subject to the
16restriction in the following sentence) without fee is hereby granted,
17provided that the above copyright notice appears in all copies, and
18that both that copyright notice and this permission notice appear in
19supporting documentation, and that the name of InfoSeek not be used in
20advertising or publicity pertaining to distribution of the software
21without specific, written prior permission. This permission is
22explicitly restricted to the copying and modification of the software
23to remain in Python, compiled Python, or other languages (such as C)
24wherein the modified or derived code is exclusively imported into a
25Python module.
26
27INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
28SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
29FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION BE LIABLE FOR ANY
30SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
31RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
32CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
33CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
34
35
36The profiler was written after only programming in Python for 3 weeks.
37As a result, it is probably clumsy code, but I don't know for sure yet
38'cause I'm a beginner :-). I did work hard to make the code run fast,
39so that profiling would be a reasonable thing to do. I tried not to
40repeat code fragments, but I'm sure I did some stuff in really awkward
41ways at times. Please send suggestions for improvements to:
Guido van Rossum789742b1996-02-12 23:17:40 +000042\code{jar@netscape.com}. I won't promise \emph{any} support. ...but
Guido van Rossumdf804f81995-03-02 12:38:39 +000043I'd appreciate the feedback.
44
45
Guido van Rossum470be141995-03-17 16:07:09 +000046\section{Introduction to the profiler}
Guido van Rossum86cb0921995-03-20 12:59:56 +000047\nodename{Profiler Introduction}
Guido van Rossumdf804f81995-03-02 12:38:39 +000048
49A \dfn{profiler} is a program that describes the run time performance
50of a program, providing a variety of statistics. This documentation
51describes the profiler functionality provided in the modules
52\code{profile} and \code{pstats.} This profiler provides
53\dfn{deterministic profiling} of any Python programs. It also
54provides a series of report generation tools to allow users to rapidly
55examine the results of a profile operation.
56
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
84loaded, and the report generating module (\code{pstats}) is not needed
85during 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
112profile.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
119can supply a file name as the second argument to the \code{run()}
120function:
121
Fred Drake19479911998-02-13 06:58:54 +0000122\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000123import profile
124profile.run("foo()", 'fooprof')
Fred Drake19479911998-02-13 06:58:54 +0000125\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000126%
Guido van Rossumbac80021997-06-02 17:29:12 +0000127\code{profile.py} can also be invoked as
128a script to profile another script. For example:
Fred Drakeab875b91998-02-13 22:07:33 +0000129\code{python} \code{/usr/local/lib/python1.4/profile.py myscript.py}
Guido van Rossumbac80021997-06-02 17:29:12 +0000130
Guido van Rossumdf804f81995-03-02 12:38:39 +0000131When you wish to review the profile, you should use the methods in the
132\code{pstats} module. Typically you would load the statistics data as
133follows:
134
Fred Drake19479911998-02-13 06:58:54 +0000135\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000136import pstats
137p = pstats.Stats('fooprof')
Fred Drake19479911998-02-13 06:58:54 +0000138\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000139%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000140The class \code{Stats} (the above code just created an instance of
141this class) has a variety of methods for manipulating and printing the
142data that was just read into \samp{p}. When you ran
143\code{profile.run()} above, what was printed was the result of three
144method calls:
145
Fred Drake19479911998-02-13 06:58:54 +0000146\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000147p.strip_dirs().sort_stats(-1).print_stats()
Fred Drake19479911998-02-13 06:58:54 +0000148\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000149%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000150The first method removed the extraneous path from all the module
151names. The second method sorted all the entries according to the
152standard module/line/name string that is printed (this is to comply
153with the semantics of the old profiler). The third method printed out
154all the statistics. You might try the following sort calls:
155
Fred Drake19479911998-02-13 06:58:54 +0000156\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000157p.sort_stats('name')
158p.print_stats()
Fred Drake19479911998-02-13 06:58:54 +0000159\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000160%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000161The first call will actually sort the list by function name, and the
162second call will print out the statistics. The following are some
163interesting calls to experiment with:
164
Fred Drake19479911998-02-13 06:58:54 +0000165\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000166p.sort_stats('cumulative').print_stats(10)
Fred Drake19479911998-02-13 06:58:54 +0000167\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000168%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000169This sorts the profile by cumulative time in a function, and then only
170prints the ten most significant lines. If you want to understand what
171algorithms are taking time, the above line is what you would use.
172
173If you were looking to see what functions were looping a lot, and
174taking a lot of time, you would do:
175
Fred Drake19479911998-02-13 06:58:54 +0000176\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000177p.sort_stats('time').print_stats(10)
Fred Drake19479911998-02-13 06:58:54 +0000178\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000179%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000180to sort according to time spent within each function, and then print
181the statistics for the top ten functions.
182
183You might also try:
184
Fred Drake19479911998-02-13 06:58:54 +0000185\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000186p.sort_stats('file').print_stats('__init__')
Fred Drake19479911998-02-13 06:58:54 +0000187\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000188%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000189This will sort all the statistics by file name, and then print out
190statistics for only the class init methods ('cause they are spelled
191with \code{__init__} in them). As one final example, you could try:
192
Fred Drake19479911998-02-13 06:58:54 +0000193\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000194p.sort_stats('time', 'cum').print_stats(.5, 'init')
Fred Drake19479911998-02-13 06:58:54 +0000195\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000196%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000197This line sorts statistics with a primary key of time, and a secondary
198key of cumulative time, and then prints out some of the statistics.
199To be specific, the list is first culled down to 50\% (re: \samp{.5})
200of its original size, then only lines containing \code{init} are
201maintained, and that sub-sub-list is printed.
202
203If you wondered what functions called the above functions, you could
204now (\samp{p} is still sorted according to the last criteria) do:
205
Fred Drake19479911998-02-13 06:58:54 +0000206\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000207p.print_callers(.5, 'init')
Fred Drake19479911998-02-13 06:58:54 +0000208\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000209%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000210and you would get a list of callers for each of the listed functions.
211
212If you want more functionality, you're going to have to read the
213manual, or guess what the following functions do:
214
Fred Drake19479911998-02-13 06:58:54 +0000215\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000216p.print_callees()
217p.add('fooprof')
Fred Drake19479911998-02-13 06:58:54 +0000218\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000219%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000220\section{What Is Deterministic Profiling?}
Guido van Rossum86cb0921995-03-20 12:59:56 +0000221\nodename{Deterministic Profiling}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000222
223\dfn{Deterministic profiling} is meant to reflect the fact that all
224\dfn{function call}, \dfn{function return}, and \dfn{exception} events
225are monitored, and precise timings are made for the intervals between
226these events (during which time the user's code is executing). In
227contrast, \dfn{statistical profiling} (which is not done by this
228module) randomly samples the effective instruction pointer, and
229deduces where time is being spent. The latter technique traditionally
230involves less overhead (as the code does not need to be instrumented),
231but provides only relative indications of where time is being spent.
232
233In Python, since there is an interpreter active during execution, the
234presence of instrumented code is not required to do deterministic
235profiling. Python automatically provides a \dfn{hook} (optional
236callback) for each event. In addition, the interpreted nature of
237Python tends to add so much overhead to execution, that deterministic
238profiling tends to only add small processing overhead in typical
239applications. The result is that deterministic profiling is not that
240expensive, yet provides extensive run time statistics about the
241execution of a Python program.
242
243Call count statistics can be used to identify bugs in code (surprising
244counts), and to identify possible inline-expansion points (high call
245counts). Internal time statistics can be used to identify ``hot
246loops'' that should be carefully optimized. Cumulative time
247statistics should be used to identify high level errors in the
248selection of algorithms. Note that the unusual handling of cumulative
249times in this profiler allows statistics for recursive implementations
250of algorithms to be directly compared to iterative implementations.
251
252
253\section{Reference Manual}
254
Fred Drake19479911998-02-13 06:58:54 +0000255\setindexsubitem{(profiler function)}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000256
257The primary entry point for the profiler is the global function
258\code{profile.run()}. It is typically used to create any profile
259information. The reports are formatted and printed using methods of
260the class \code{pstats.Stats}. The following is a description of all
261of these standard entry points and functions. For a more in-depth
262view of some of the code, consider reading the later section on
263Profiler Extensions, which includes discussion of how to derive
264``better'' profilers from the classes presented, or reading the source
265code for these modules.
266
Guido van Rossum470be141995-03-17 16:07:09 +0000267\begin{funcdesc}{profile.run}{string\optional{\, filename\optional{\, ...}}}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000268
269This function takes a single argument that has can be passed to the
270\code{exec} statement, and an optional file name. In all cases this
271routine attempts to \code{exec} its first argument, and gather profiling
272statistics from the execution. If no file name is present, then this
273function automatically prints a simple profiling report, sorted by the
274standard name string (file/line/function-name) that is presented in
275each line. The following is a typical output from such a call:
276
Fred Drake19479911998-02-13 06:58:54 +0000277\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 ...
Fred Drake19479911998-02-13 06:58:54 +0000287\end{verbatim}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000288
289The first line indicates that this profile was generated by the call:\\
290\code{profile.run('main()')}, and hence the exec'ed string is
291\code{'main()'}. The second line indicates that 2706 calls were
292monitored. Of those calls, 2004 were \dfn{primitive}. We define
293\dfn{primitive} to mean that the call was not induced via recursion.
294The next line: \code{Ordered by:\ standard name}, indicates that
295the text string in the far right column was used to sort the output.
296The column headings include:
297
298\begin{description}
299
300\item[ncalls ]
301for the number of calls,
302
303\item[tottime ]
304for the total time spent in the given function (and excluding time
305made in calls to sub-functions),
306
307\item[percall ]
308is the quotient of \code{tottime} divided by \code{ncalls}
309
310\item[cumtime ]
311is the total time spent in this and all subfunctions (i.e., from
312invocation till exit). This figure is accurate \emph{even} for recursive
313functions.
314
315\item[percall ]
316is the quotient of \code{cumtime} divided by primitive calls
317
318\item[filename:lineno(function) ]
319provides the respective data of each function
320
321\end{description}
322
323When there are two numbers in the first column (e.g.: \samp{43/3}),
324then the latter is the number of primitive calls, and the former is
325the actual number of calls. Note that when the function does not
326recurse, these two values are the same, and only the single figure is
327printed.
Guido van Rossum96628a91995-04-10 11:34:00 +0000328
Guido van Rossumdf804f81995-03-02 12:38:39 +0000329\end{funcdesc}
330
331\begin{funcdesc}{pstats.Stats}{filename\optional{\, ...}}
332This class constructor creates an instance of a ``statistics object''
333from a \var{filename} (or set of filenames). \code{Stats} objects are
334manipulated by methods, in order to print useful reports.
335
336The file selected by the above constructor must have been created by
337the corresponding version of \code{profile}. To be specific, there is
338\emph{NO} file compatibility guaranteed with future versions of this
339profiler, and there is no compatibility with files produced by other
340profilers (e.g., the old system profiler).
341
342If several files are provided, all the statistics for identical
343functions will be coalesced, so that an overall view of several
344processes can be considered in a single report. If additional files
345need to be combined with data in an existing \code{Stats} object, the
346\code{add()} method can be used.
347\end{funcdesc}
348
349
Guido van Rossum470be141995-03-17 16:07:09 +0000350\subsection{The \sectcode{Stats} Class}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000351
Fred Drake19479911998-02-13 06:58:54 +0000352\setindexsubitem{(Stats method)}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000353
354\begin{funcdesc}{strip_dirs}{}
Guido van Rossum470be141995-03-17 16:07:09 +0000355This method for the \code{Stats} class removes all leading path information
Guido van Rossumdf804f81995-03-02 12:38:39 +0000356from file names. It is very useful in reducing the size of the
357printout to fit within (close to) 80 columns. This method modifies
358the object, and the stripped information is lost. After performing a
359strip operation, the object is considered to have its entries in a
360``random'' order, as it was just after object initialization and
361loading. If \code{strip_dirs()} causes two function names to be
362indistinguishable (i.e., they are on the same line of the same
363filename, and have the same function name), then the statistics for
364these two entries are accumulated into a single entry.
365\end{funcdesc}
366
367
368\begin{funcdesc}{add}{filename\optional{\, ...}}
Guido van Rossum470be141995-03-17 16:07:09 +0000369This method of the \code{Stats} class accumulates additional profiling
Guido van Rossumdf804f81995-03-02 12:38:39 +0000370information into the current profiling object. Its arguments should
371refer to filenames created by the corresponding version of
372\code{profile.run()}. Statistics for identically named (re: file,
373line, name) functions are automatically accumulated into single
374function statistics.
375\end{funcdesc}
376
377\begin{funcdesc}{sort_stats}{key\optional{\, ...}}
Guido van Rossum470be141995-03-17 16:07:09 +0000378This method modifies the \code{Stats} object by sorting it according to the
Guido van Rossumdf804f81995-03-02 12:38:39 +0000379supplied criteria. The argument is typically a string identifying the
380basis of a sort (example: \code{"time"} or \code{"name"}).
381
382When more than one key is provided, then additional keys are used as
383secondary criteria when the there is equality in all keys selected
384before them. For example, sort_stats('name', 'file') will sort all
385the entries according to their function name, and resolve all ties
386(identical function names) by sorting by file name.
387
388Abbreviations can be used for any key names, as long as the
389abbreviation is unambiguous. The following are the keys currently
390defined:
391
392\begin{tableii}{|l|l|}{code}{Valid Arg}{Meaning}
393\lineii{"calls"}{call count}
394\lineii{"cumulative"}{cumulative time}
395\lineii{"file"}{file name}
396\lineii{"module"}{file name}
397\lineii{"pcalls"}{primitive call count}
398\lineii{"line"}{line number}
399\lineii{"name"}{function name}
400\lineii{"nfl"}{name/file/line}
401\lineii{"stdname"}{standard name}
402\lineii{"time"}{internal time}
403\end{tableii}
404
405Note that all sorts on statistics are in descending order (placing
406most time consuming items first), where as name, file, and line number
407searches are in ascending order (i.e., alphabetical). The subtle
408distinction between \code{"nfl"} and \code{"stdname"} is that the
409standard name is a sort of the name as printed, which means that the
410embedded line numbers get compared in an odd way. For example, lines
4113, 20, and 40 would (if the file names were the same) appear in the
412string order 20, 3 and 40. In contrast, \code{"nfl"} does a numeric
413compare of the line numbers. In fact, \code{sort_stats("nfl")} is the
414same as \code{sort_stats("name", "file", "line")}.
415
416For compatibility with the old profiler, the numeric arguments
417\samp{-1}, \samp{0}, \samp{1}, and \samp{2} are permitted. They are
418interpreted as \code{"stdname"}, \code{"calls"}, \code{"time"}, and
419\code{"cumulative"} respectively. If this old style format (numeric)
420is used, only one sort key (the numeric key) will be used, and
421additional arguments will be silently ignored.
422\end{funcdesc}
423
424
425\begin{funcdesc}{reverse_order}{}
Guido van Rossum470be141995-03-17 16:07:09 +0000426This method for the \code{Stats} class reverses the ordering of the basic
Guido van Rossumdf804f81995-03-02 12:38:39 +0000427list within the object. This method is provided primarily for
428compatibility with the old profiler. Its utility is questionable
429now that ascending vs descending order is properly selected based on
430the sort key of choice.
431\end{funcdesc}
432
433\begin{funcdesc}{print_stats}{restriction\optional{\, ...}}
Guido van Rossum470be141995-03-17 16:07:09 +0000434This method for the \code{Stats} class prints out a report as described
Guido van Rossumdf804f81995-03-02 12:38:39 +0000435in the \code{profile.run()} definition.
436
437The order of the printing is based on the last \code{sort_stats()}
438operation done on the object (subject to caveats in \code{add()} and
439\code{strip_dirs())}.
440
441The arguments provided (if any) can be used to limit the list down to
442the significant entries. Initially, the list is taken to be the
443complete set of profiled functions. Each restriction is either an
444integer (to select a count of lines), or a decimal fraction between
4450.0 and 1.0 inclusive (to select a percentage of lines), or a regular
Guido van Rossum364e6431997-11-18 15:28:46 +0000446expression (to pattern match the standard name that is printed; as of
447Python 1.5b1, this uses the Perl-style regular expression syntax
448defined by the \code{re} module). If several restrictions are
449provided, then they are applied sequentially. For example:
Guido van Rossumdf804f81995-03-02 12:38:39 +0000450
Fred Drake19479911998-02-13 06:58:54 +0000451\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000452print_stats(.1, "foo:")
Fred Drake19479911998-02-13 06:58:54 +0000453\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000454%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000455would first limit the printing to first 10\% of list, and then only
456print functions that were part of filename \samp{.*foo:}. In
457contrast, the command:
458
Fred Drake19479911998-02-13 06:58:54 +0000459\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000460print_stats("foo:", .1)
Fred Drake19479911998-02-13 06:58:54 +0000461\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000462%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000463would limit the list to all functions having file names \samp{.*foo:},
464and then proceed to only print the first 10\% of them.
465\end{funcdesc}
466
467
468\begin{funcdesc}{print_callers}{restrictions\optional{\, ...}}
Guido van Rossum470be141995-03-17 16:07:09 +0000469This method for the \code{Stats} class prints a list of all functions
Guido van Rossumdf804f81995-03-02 12:38:39 +0000470that called each function in the profiled database. The ordering is
471identical to that provided by \code{print_stats()}, and the definition
472of the restricting argument is also identical. For convenience, a
473number is shown in parentheses after each caller to show how many
474times this specific call was made. A second non-parenthesized number
475is the cumulative time spent in the function at the right.
476\end{funcdesc}
477
478\begin{funcdesc}{print_callees}{restrictions\optional{\, ...}}
Guido van Rossum470be141995-03-17 16:07:09 +0000479This method for the \code{Stats} class prints a list of all function
Guido van Rossumdf804f81995-03-02 12:38:39 +0000480that were called by the indicated function. Aside from this reversal
481of direction of calls (re: called vs was called by), the arguments and
482ordering are identical to the \code{print_callers()} method.
483\end{funcdesc}
484
485\begin{funcdesc}{ignore}{}
Guido van Rossum470be141995-03-17 16:07:09 +0000486This method of the \code{Stats} class is used to dispose of the value
Guido van Rossumdf804f81995-03-02 12:38:39 +0000487returned by earlier methods. All standard methods in this class
488return the instance that is being processed, so that the commands can
489be strung together. For example:
490
Fred Drake19479911998-02-13 06:58:54 +0000491\begin{verbatim}
Guido van Rossum96628a91995-04-10 11:34:00 +0000492pstats.Stats('foofile').strip_dirs().sort_stats('cum') \
493 .print_stats().ignore()
Fred Drake19479911998-02-13 06:58:54 +0000494\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000495%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000496would perform all the indicated functions, but it would not return
Guido van Rossum470be141995-03-17 16:07:09 +0000497the final reference to the \code{Stats} instance.%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000498\footnote{
499This was once necessary, when Python would print any unused expression
500result that was not \code{None}. The method is still defined for
501backward compatibility.
502}
503\end{funcdesc}
504
505
506\section{Limitations}
507
508There are two fundamental limitations on this profiler. The first is
509that it relies on the Python interpreter to dispatch \dfn{call},
510\dfn{return}, and \dfn{exception} events. Compiled C code does not
511get interpreted, and hence is ``invisible'' to the profiler. All time
512spent in C code (including builtin functions) will be charged to the
Guido van Rossumcca8d2b1995-03-22 15:48:46 +0000513Python function that invoked the C code. If the C code calls out
Guido van Rossumdf804f81995-03-02 12:38:39 +0000514to some native Python code, then those calls will be profiled
515properly.
516
517The second limitation has to do with accuracy of timing information.
518There is a fundamental problem with deterministic profilers involving
519accuracy. The most obvious restriction is that the underlying ``clock''
520is only ticking at a rate (typically) of about .001 seconds. Hence no
521measurements will be more accurate that that underlying clock. If
522enough measurements are taken, then the ``error'' will tend to average
523out. Unfortunately, removing this first error induces a second source
524of error...
525
526The second problem is that it ``takes a while'' from when an event is
527dispatched until the profiler's call to get the time actually
528\emph{gets} the state of the clock. Similarly, there is a certain lag
529when exiting the profiler event handler from the time that the clock's
530value was obtained (and then squirreled away), until the user's code
531is once again executing. As a result, functions that are called many
532times, or call many functions, will typically accumulate this error.
533The error that accumulates in this fashion is typically less than the
534accuracy of the clock (i.e., less than one clock tick), but it
535\emph{can} accumulate and become very significant. This profiler
536provides a means of calibrating itself for a given platform so that
537this error can be probabilistically (i.e., on the average) removed.
538After the profiler is calibrated, it will be more accurate (in a least
539square sense), but it will sometimes produce negative numbers (when
540call counts are exceptionally low, and the gods of probability work
541against you :-). ) Do \emph{NOT} be alarmed by negative numbers in
542the profile. They should \emph{only} appear if you have calibrated
543your profiler, and the results are actually better than without
544calibration.
545
546
547\section{Calibration}
548
549The profiler class has a hard coded constant that is added to each
550event handling time to compensate for the overhead of calling the time
551function, and socking away the results. The following procedure can
552be used to obtain this constant for a given platform (see discussion
553in section Limitations above).
554
Fred Drake19479911998-02-13 06:58:54 +0000555\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000556import profile
557pr = profile.Profile()
558pr.calibrate(100)
559pr.calibrate(100)
560pr.calibrate(100)
Fred Drake19479911998-02-13 06:58:54 +0000561\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000562%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000563The argument to calibrate() is the number of times to try to do the
564sample calls to get the CPU times. If your computer is \emph{very}
565fast, you might have to do:
566
Fred Drake19479911998-02-13 06:58:54 +0000567\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000568pr.calibrate(1000)
Fred Drake19479911998-02-13 06:58:54 +0000569\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000570%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000571or even:
572
Fred Drake19479911998-02-13 06:58:54 +0000573\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000574pr.calibrate(10000)
Fred Drake19479911998-02-13 06:58:54 +0000575\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000576%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000577The object of this exercise is to get a fairly consistent result.
578When you have a consistent answer, you are ready to use that number in
579the source code. For a Sun Sparcstation 1000 running Solaris 2.3, the
580magical number is about .00053. If you have a choice, you are better
581off with a smaller constant, and your results will ``less often'' show
582up as negative in profile statistics.
583
584The following shows how the trace_dispatch() method in the Profile
585class should be modified to install the calibration constant on a Sun
586Sparcstation 1000:
587
Fred Drake19479911998-02-13 06:58:54 +0000588\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000589def trace_dispatch(self, frame, event, arg):
590 t = self.timer()
591 t = t[0] + t[1] - self.t - .00053 # Calibration constant
592
593 if self.dispatch[event](frame,t):
Guido van Rossumdf804f81995-03-02 12:38:39 +0000594 t = self.timer()
Guido van Rossume47da0a1997-07-17 16:34:52 +0000595 self.t = t[0] + t[1]
596 else:
597 r = self.timer()
598 self.t = r[0] + r[1] - t # put back unrecorded delta
599 return
Fred Drake19479911998-02-13 06:58:54 +0000600\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000601%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000602Note that if there is no calibration constant, then the line
603containing the callibration constant should simply say:
604
Fred Drake19479911998-02-13 06:58:54 +0000605\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000606t = t[0] + t[1] - self.t # no calibration constant
Fred Drake19479911998-02-13 06:58:54 +0000607\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000608%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000609You can also achieve the same results using a derived class (and the
610profiler will actually run equally fast!!), but the above method is
611the simplest to use. I could have made the profiler ``self
612calibrating'', but it would have made the initialization of the
613profiler class slower, and would have required some \emph{very} fancy
614coding, or else the use of a variable where the constant \samp{.00053}
615was placed in the code shown. This is a \strong{VERY} critical
616performance section, and there is no reason to use a variable lookup
617at this point, when a constant can be used.
618
619
Guido van Rossum86cb0921995-03-20 12:59:56 +0000620\section{Extensions --- Deriving Better Profilers}
621\nodename{Profiler Extensions}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000622
623The \code{Profile} class of module \code{profile} was written so that
624derived classes could be developed to extend the profiler. Rather
625than describing all the details of such an effort, I'll just present
626the following two examples of derived classes that can be used to do
627profiling. If the reader is an avid Python programmer, then it should
628be possible to use these as a model and create similar (and perchance
629better) profile classes.
630
631If all you want to do is change how the timer is called, or which
632timer function is used, then the basic class has an option for that in
633the constructor for the class. Consider passing the name of a
634function to call into the constructor:
635
Fred Drake19479911998-02-13 06:58:54 +0000636\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000637pr = profile.Profile(your_time_func)
Fred Drake19479911998-02-13 06:58:54 +0000638\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000639%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000640The resulting profiler will call \code{your_time_func()} instead of
641\code{os.times()}. The function should return either a single number
642or a list of numbers (like what \code{os.times()} returns). If the
643function returns a single time number, or the list of returned numbers
644has length 2, then you will get an especially fast version of the
645dispatch routine.
646
647Be warned that you \emph{should} calibrate the profiler class for the
648timer function that you choose. For most machines, a timer that
649returns a lone integer value will provide the best results in terms of
650low overhead during profiling. (os.times is \emph{pretty} bad, 'cause
651it returns a tuple of floating point values, so all arithmetic is
652floating point in the profiler!). If you want to substitute a
653better timer in the cleanest fashion, you should derive a class, and
654simply put in the replacement dispatch method that better handles your
655timer call, along with the appropriate calibration constant :-).
656
657
658\subsection{OldProfile Class}
659
660The following derived profiler simulates the old style profiler,
661providing errant results on recursive functions. The reason for the
662usefulness of this profiler is that it runs faster (i.e., less
663overhead) than the old profiler. It still creates all the caller
664stats, and is quite useful when there is \emph{no} recursion in the
665user's code. It is also a lot more accurate than the old profiler, as
666it does not charge all its overhead time to the user's code.
667
Fred Drake19479911998-02-13 06:58:54 +0000668\begin{verbatim}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000669class OldProfile(Profile):
670
671 def trace_dispatch_exception(self, frame, t):
672 rt, rtt, rct, rfn, rframe, rcur = self.cur
673 if rcur and not rframe is frame:
674 return self.trace_dispatch_return(rframe, t)
675 return 0
676
677 def trace_dispatch_call(self, frame, t):
678 fn = `frame.f_code`
679
680 self.cur = (t, 0, 0, fn, frame, self.cur)
681 if self.timings.has_key(fn):
682 tt, ct, callers = self.timings[fn]
683 self.timings[fn] = tt, ct, callers
684 else:
685 self.timings[fn] = 0, 0, {}
686 return 1
687
688 def trace_dispatch_return(self, frame, t):
689 rt, rtt, rct, rfn, frame, rcur = self.cur
690 rtt = rtt + t
691 sft = rtt + rct
692
693 pt, ptt, pct, pfn, pframe, pcur = rcur
694 self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur
695
696 tt, ct, callers = self.timings[rfn]
697 if callers.has_key(pfn):
698 callers[pfn] = callers[pfn] + 1
699 else:
700 callers[pfn] = 1
701 self.timings[rfn] = tt+rtt, ct + sft, callers
702
703 return 1
704
705
706 def snapshot_stats(self):
707 self.stats = {}
708 for func in self.timings.keys():
709 tt, ct, callers = self.timings[func]
710 nor_func = self.func_normalize(func)
711 nor_callers = {}
712 nc = 0
713 for func_caller in callers.keys():
714 nor_callers[self.func_normalize(func_caller)]=\
715 callers[func_caller]
716 nc = nc + callers[func_caller]
717 self.stats[nor_func] = nc, nc, tt, ct, nor_callers
Fred Drake19479911998-02-13 06:58:54 +0000718\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000719%
Guido van Rossumdf804f81995-03-02 12:38:39 +0000720\subsection{HotProfile Class}
721
722This profiler is the fastest derived profile example. It does not
723calculate caller-callee relationships, and does not calculate
724cumulative time under a function. It only calculates time spent in a
725function, so it runs very quickly (re: very low overhead). In truth,
726the basic profiler is so fast, that is probably not worth the savings
727to give up the data, but this class still provides a nice example.
728
Fred Drake19479911998-02-13 06:58:54 +0000729\begin{verbatim}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000730class HotProfile(Profile):
731
732 def trace_dispatch_exception(self, frame, t):
733 rt, rtt, rfn, rframe, rcur = self.cur
734 if rcur and not rframe is frame:
735 return self.trace_dispatch_return(rframe, t)
736 return 0
737
738 def trace_dispatch_call(self, frame, t):
739 self.cur = (t, 0, frame, self.cur)
740 return 1
741
742 def trace_dispatch_return(self, frame, t):
743 rt, rtt, frame, rcur = self.cur
744
745 rfn = `frame.f_code`
746
747 pt, ptt, pframe, pcur = rcur
748 self.cur = pt, ptt+rt, pframe, pcur
749
750 if self.timings.has_key(rfn):
751 nc, tt = self.timings[rfn]
752 self.timings[rfn] = nc + 1, rt + rtt + tt
753 else:
754 self.timings[rfn] = 1, rt + rtt
755
756 return 1
757
758
759 def snapshot_stats(self):
760 self.stats = {}
761 for func in self.timings.keys():
762 nc, tt = self.timings[func]
763 nor_func = self.func_normalize(func)
764 self.stats[nor_func] = nc, nc, tt, 0, {}
Fred Drake19479911998-02-13 06:58:54 +0000765\end{verbatim}