blob: fa0f6b31a704c2598111382ee90a2f9e3d555925 [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
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000101\section{Instant Users Manual \label{profile-instant}}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000102
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}
Fred Drakeb9f1f6d1999-04-21 21:43:17 +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}
Fred Drakeb9f1f6d1999-04-21 21:43:17 +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
Nicholas Bastin824b1b22004-03-23 18:44:39 +0000134\file{profile.py} accepts two optional arguments on the command line:
135
136\begin{verbatim}
137profile.py [-o output_file] [-s sort_order]
138\end{verbatim}
139
140\samp{-s} only applies to stdout (i.e. \samp{-o} is not supplied.
141Look in the \class{Stats} documentation for valid sort values.
142
Guido van Rossumdf804f81995-03-02 12:38:39 +0000143When you wish to review the profile, you should use the methods in the
Fred Drake8fa5eb81998-02-27 05:23:37 +0000144\module{pstats} module. Typically you would load the statistics data as
Guido van Rossumdf804f81995-03-02 12:38:39 +0000145follows:
146
Fred Drake19479911998-02-13 06:58:54 +0000147\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000148import pstats
149p = pstats.Stats('fooprof')
Fred Drake19479911998-02-13 06:58:54 +0000150\end{verbatim}
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000151
Fred Drake8fa5eb81998-02-27 05:23:37 +0000152The class \class{Stats} (the above code just created an instance of
Guido van Rossumdf804f81995-03-02 12:38:39 +0000153this class) has a variety of methods for manipulating and printing the
154data that was just read into \samp{p}. When you ran
Fred Drake8fa5eb81998-02-27 05:23:37 +0000155\function{profile.run()} above, what was printed was the result of three
Guido van Rossumdf804f81995-03-02 12:38:39 +0000156method calls:
157
Fred Drake19479911998-02-13 06:58:54 +0000158\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000159p.strip_dirs().sort_stats(-1).print_stats()
Fred Drake19479911998-02-13 06:58:54 +0000160\end{verbatim}
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000161
Guido van Rossumdf804f81995-03-02 12:38:39 +0000162The first method removed the extraneous path from all the module
163names. The second method sorted all the entries according to the
164standard module/line/name string that is printed (this is to comply
165with the semantics of the old profiler). The third method printed out
166all the statistics. You might try the following sort calls:
167
Fred Drake19479911998-02-13 06:58:54 +0000168\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000169p.sort_stats('name')
170p.print_stats()
Fred Drake19479911998-02-13 06:58:54 +0000171\end{verbatim}
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000172
Guido van Rossumdf804f81995-03-02 12:38:39 +0000173The first call will actually sort the list by function name, and the
174second call will print out the statistics. The following are some
175interesting calls to experiment with:
176
Fred Drake19479911998-02-13 06:58:54 +0000177\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000178p.sort_stats('cumulative').print_stats(10)
Fred Drake19479911998-02-13 06:58:54 +0000179\end{verbatim}
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000180
Guido van Rossumdf804f81995-03-02 12:38:39 +0000181This sorts the profile by cumulative time in a function, and then only
182prints the ten most significant lines. If you want to understand what
183algorithms are taking time, the above line is what you would use.
184
185If you were looking to see what functions were looping a lot, and
186taking a lot of time, you would do:
187
Fred Drake19479911998-02-13 06:58:54 +0000188\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000189p.sort_stats('time').print_stats(10)
Fred Drake19479911998-02-13 06:58:54 +0000190\end{verbatim}
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000191
Guido van Rossumdf804f81995-03-02 12:38:39 +0000192to sort according to time spent within each function, and then print
193the statistics for the top ten functions.
194
195You might also try:
196
Fred Drake19479911998-02-13 06:58:54 +0000197\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000198p.sort_stats('file').print_stats('__init__')
Fred Drake19479911998-02-13 06:58:54 +0000199\end{verbatim}
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000200
Guido van Rossumdf804f81995-03-02 12:38:39 +0000201This will sort all the statistics by file name, and then print out
202statistics for only the class init methods ('cause they are spelled
Fred Drake8fa5eb81998-02-27 05:23:37 +0000203with \samp{__init__} in them). As one final example, you could try:
Guido van Rossumdf804f81995-03-02 12:38:39 +0000204
Fred Drake19479911998-02-13 06:58:54 +0000205\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000206p.sort_stats('time', 'cum').print_stats(.5, 'init')
Fred Drake19479911998-02-13 06:58:54 +0000207\end{verbatim}
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000208
Guido van Rossumdf804f81995-03-02 12:38:39 +0000209This line sorts statistics with a primary key of time, and a secondary
210key of cumulative time, and then prints out some of the statistics.
211To be specific, the list is first culled down to 50\% (re: \samp{.5})
212of its original size, then only lines containing \code{init} are
213maintained, and that sub-sub-list is printed.
214
215If you wondered what functions called the above functions, you could
216now (\samp{p} is still sorted according to the last criteria) do:
217
Fred Drake19479911998-02-13 06:58:54 +0000218\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000219p.print_callers(.5, 'init')
Fred Drake19479911998-02-13 06:58:54 +0000220\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000221
Tim Peters0a1fc4e2001-10-07 03:12:08 +0000222and you would get a list of callers for each of the listed functions.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000223
224If you want more functionality, you're going to have to read the
225manual, or guess what the following functions do:
226
Fred Drake19479911998-02-13 06:58:54 +0000227\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000228p.print_callees()
229p.add('fooprof')
Fred Drake19479911998-02-13 06:58:54 +0000230\end{verbatim}
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000231
Eric S. Raymond4f3980d2001-04-13 00:23:01 +0000232Invoked as a script, the \module{pstats} module is a statistics
233browser for reading and examining profile dumps. It has a simple
Fred Drakea3e56a62001-04-13 14:34:58 +0000234line-oriented interface (implemented using \refmodule{cmd}) and
Eric S. Raymond4f3980d2001-04-13 00:23:01 +0000235interactive help.
236
Guido van Rossumdf804f81995-03-02 12:38:39 +0000237\section{What Is Deterministic Profiling?}
Guido van Rossum86cb0921995-03-20 12:59:56 +0000238\nodename{Deterministic Profiling}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000239
240\dfn{Deterministic profiling} is meant to reflect the fact that all
Fred Drakea3e56a62001-04-13 14:34:58 +0000241\emph{function call}, \emph{function return}, and \emph{exception} events
Guido van Rossumdf804f81995-03-02 12:38:39 +0000242are monitored, and precise timings are made for the intervals between
243these events (during which time the user's code is executing). In
244contrast, \dfn{statistical profiling} (which is not done by this
245module) randomly samples the effective instruction pointer, and
246deduces where time is being spent. The latter technique traditionally
247involves less overhead (as the code does not need to be instrumented),
248but provides only relative indications of where time is being spent.
249
250In Python, since there is an interpreter active during execution, the
251presence of instrumented code is not required to do deterministic
252profiling. Python automatically provides a \dfn{hook} (optional
253callback) for each event. In addition, the interpreted nature of
254Python tends to add so much overhead to execution, that deterministic
255profiling tends to only add small processing overhead in typical
256applications. The result is that deterministic profiling is not that
257expensive, yet provides extensive run time statistics about the
258execution of a Python program.
259
260Call count statistics can be used to identify bugs in code (surprising
261counts), and to identify possible inline-expansion points (high call
262counts). Internal time statistics can be used to identify ``hot
263loops'' that should be carefully optimized. Cumulative time
264statistics should be used to identify high level errors in the
265selection of algorithms. Note that the unusual handling of cumulative
266times in this profiler allows statistics for recursive implementations
267of algorithms to be directly compared to iterative implementations.
268
269
270\section{Reference Manual}
Fred Drakeb91e9341998-07-23 17:59:49 +0000271
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000272\declaremodule{standard}{profile}
273\modulesynopsis{Python profiler}
Fred Drakeb91e9341998-07-23 17:59:49 +0000274
Guido van Rossumdf804f81995-03-02 12:38:39 +0000275
Guido van Rossumdf804f81995-03-02 12:38:39 +0000276
277The primary entry point for the profiler is the global function
Fred Drake8fa5eb81998-02-27 05:23:37 +0000278\function{profile.run()}. It is typically used to create any profile
Guido van Rossumdf804f81995-03-02 12:38:39 +0000279information. The reports are formatted and printed using methods of
Fred Drake8fa5eb81998-02-27 05:23:37 +0000280the class \class{pstats.Stats}. The following is a description of all
Guido van Rossumdf804f81995-03-02 12:38:39 +0000281of these standard entry points and functions. For a more in-depth
282view of some of the code, consider reading the later section on
283Profiler Extensions, which includes discussion of how to derive
284``better'' profilers from the classes presented, or reading the source
285code for these modules.
286
Nicholas Bastin1eb4bfc2004-03-22 20:12:56 +0000287\begin{funcdesc}{run}{command\optional{, filename}}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000288
289This function takes a single argument that has can be passed to the
Fred Drake8fa5eb81998-02-27 05:23:37 +0000290\keyword{exec} statement, and an optional file name. In all cases this
291routine attempts to \keyword{exec} its first argument, and gather profiling
Guido van Rossumdf804f81995-03-02 12:38:39 +0000292statistics from the execution. If no file name is present, then this
293function automatically prints a simple profiling report, sorted by the
294standard name string (file/line/function-name) that is presented in
295each line. The following is a typical output from such a call:
296
Fred Drake19479911998-02-13 06:58:54 +0000297\begin{verbatim}
Guido van Rossum96628a91995-04-10 11:34:00 +0000298 main()
299 2706 function calls (2004 primitive calls) in 4.504 CPU seconds
Guido van Rossumdf804f81995-03-02 12:38:39 +0000300
Guido van Rossum96628a91995-04-10 11:34:00 +0000301Ordered by: standard name
Guido van Rossumdf804f81995-03-02 12:38:39 +0000302
Guido van Rossum96628a91995-04-10 11:34:00 +0000303ncalls tottime percall cumtime percall filename:lineno(function)
304 2 0.006 0.003 0.953 0.477 pobject.py:75(save_objects)
305 43/3 0.533 0.012 0.749 0.250 pobject.py:99(evaluate)
306 ...
Fred Drake19479911998-02-13 06:58:54 +0000307\end{verbatim}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000308
309The first line indicates that this profile was generated by the call:\\
310\code{profile.run('main()')}, and hence the exec'ed string is
311\code{'main()'}. The second line indicates that 2706 calls were
312monitored. Of those calls, 2004 were \dfn{primitive}. We define
313\dfn{primitive} to mean that the call was not induced via recursion.
314The next line: \code{Ordered by:\ standard name}, indicates that
315the text string in the far right column was used to sort the output.
316The column headings include:
317
318\begin{description}
319
320\item[ncalls ]
Tim Peters0a1fc4e2001-10-07 03:12:08 +0000321for the number of calls,
Guido van Rossumdf804f81995-03-02 12:38:39 +0000322
323\item[tottime ]
324for the total time spent in the given function (and excluding time
325made in calls to sub-functions),
326
327\item[percall ]
328is the quotient of \code{tottime} divided by \code{ncalls}
329
330\item[cumtime ]
Fred Drake907e76b2001-07-06 20:30:11 +0000331is the total time spent in this and all subfunctions (from invocation
332till exit). This figure is accurate \emph{even} for recursive
Guido van Rossumdf804f81995-03-02 12:38:39 +0000333functions.
334
335\item[percall ]
336is the quotient of \code{cumtime} divided by primitive calls
337
338\item[filename:lineno(function) ]
339provides the respective data of each function
340
341\end{description}
342
Fred Drake907e76b2001-07-06 20:30:11 +0000343When there are two numbers in the first column (for example,
344\samp{43/3}), then the latter is the number of primitive calls, and
345the former is the actual number of calls. Note that when the function
346does not recurse, these two values are the same, and only the single
347figure is printed.
Guido van Rossum96628a91995-04-10 11:34:00 +0000348
Guido van Rossumdf804f81995-03-02 12:38:39 +0000349\end{funcdesc}
350
Nicholas Bastin1eb4bfc2004-03-22 20:12:56 +0000351\begin{funcdesc}{runctx}{command, globals, locals\optional{, filename}}
352This function is similar to \function{profile.run()}, with added
353arguments to supply the globals and locals dictionaries for the
354\var{command} string.
355\end{funcdesc}
356
Fred Drake8fa5eb81998-02-27 05:23:37 +0000357Analysis of the profiler data is done using this class from the
358\module{pstats} module:
359
Fred Drake8fe533e1998-03-27 05:27:08 +0000360% now switch modules....
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000361% (This \stmodindex use may be hard to change ;-( )
Fred Drake8fe533e1998-03-27 05:27:08 +0000362\stmodindex{pstats}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000363
Fred Drakecce10901998-03-17 06:33:25 +0000364\begin{classdesc}{Stats}{filename\optional{, ...}}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000365This class constructor creates an instance of a ``statistics object''
Fred Drake8fa5eb81998-02-27 05:23:37 +0000366from a \var{filename} (or set of filenames). \class{Stats} objects are
Guido van Rossumdf804f81995-03-02 12:38:39 +0000367manipulated by methods, in order to print useful reports.
368
369The file selected by the above constructor must have been created by
Fred Drake8fa5eb81998-02-27 05:23:37 +0000370the corresponding version of \module{profile}. To be specific, there is
371\emph{no} file compatibility guaranteed with future versions of this
Guido van Rossumdf804f81995-03-02 12:38:39 +0000372profiler, and there is no compatibility with files produced by other
Fred Drake907e76b2001-07-06 20:30:11 +0000373profilers (such as the old system profiler).
Guido van Rossumdf804f81995-03-02 12:38:39 +0000374
375If several files are provided, all the statistics for identical
376functions will be coalesced, so that an overall view of several
377processes can be considered in a single report. If additional files
Fred Drake8fa5eb81998-02-27 05:23:37 +0000378need to be combined with data in an existing \class{Stats} object, the
379\method{add()} method can be used.
380\end{classdesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000381
382
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000383\subsection{The \class{Stats} Class \label{profile-stats}}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000384
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000385\class{Stats} objects have the following methods:
Guido van Rossumdf804f81995-03-02 12:38:39 +0000386
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000387\begin{methoddesc}[Stats]{strip_dirs}{}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000388This method for the \class{Stats} class removes all leading path
389information from file names. It is very useful in reducing the size
390of the printout to fit within (close to) 80 columns. This method
391modifies the object, and the stripped information is lost. After
392performing a strip operation, the object is considered to have its
393entries in a ``random'' order, as it was just after object
394initialization and loading. If \method{strip_dirs()} causes two
Fred Drake907e76b2001-07-06 20:30:11 +0000395function names to be indistinguishable (they are on the same
Fred Drake8fa5eb81998-02-27 05:23:37 +0000396line of the same filename, and have the same function name), then the
397statistics for these two entries are accumulated into a single entry.
Fred Drake8fe533e1998-03-27 05:27:08 +0000398\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000399
400
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000401\begin{methoddesc}[Stats]{add}{filename\optional{, ...}}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000402This method of the \class{Stats} class accumulates additional
403profiling information into the current profiling object. Its
404arguments should refer to filenames created by the corresponding
405version of \function{profile.run()}. Statistics for identically named
406(re: file, line, name) functions are automatically accumulated into
407single function statistics.
Fred Drake8fe533e1998-03-27 05:27:08 +0000408\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000409
Fred Drake126d3662003-05-14 14:29:27 +0000410\begin{methoddesc}[Stats]{dump_stats}{filename}
411Save the data loaded into the \class{Stats} object to a file named
412\var{filename}. The file is created if it does not exist, and is
413overwritten if it already exists. This is equivalent to the method of
414the same name on the \class{profile.Profile} class.
415\versionadded{2.3}
416\end{methoddesc}
417
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000418\begin{methoddesc}[Stats]{sort_stats}{key\optional{, ...}}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000419This method modifies the \class{Stats} object by sorting it according
420to the supplied criteria. The argument is typically a string
Fred Drake2cb824c1998-04-09 18:10:35 +0000421identifying the basis of a sort (example: \code{'time'} or
422\code{'name'}).
Guido van Rossumdf804f81995-03-02 12:38:39 +0000423
424When more than one key is provided, then additional keys are used as
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000425secondary criteria when there is equality in all keys selected
Fred Drake8fa5eb81998-02-27 05:23:37 +0000426before them. For example, \samp{sort_stats('name', 'file')} will sort
427all the entries according to their function name, and resolve all ties
Guido van Rossumdf804f81995-03-02 12:38:39 +0000428(identical function names) by sorting by file name.
429
430Abbreviations can be used for any key names, as long as the
431abbreviation is unambiguous. The following are the keys currently
Tim Peters0a1fc4e2001-10-07 03:12:08 +0000432defined:
Guido van Rossumdf804f81995-03-02 12:38:39 +0000433
Fred Drakeee601911998-04-11 20:53:03 +0000434\begin{tableii}{l|l}{code}{Valid Arg}{Meaning}
Fred Drake5dabeed1998-04-03 07:02:35 +0000435 \lineii{'calls'}{call count}
436 \lineii{'cumulative'}{cumulative time}
437 \lineii{'file'}{file name}
438 \lineii{'module'}{file name}
439 \lineii{'pcalls'}{primitive call count}
440 \lineii{'line'}{line number}
441 \lineii{'name'}{function name}
442 \lineii{'nfl'}{name/file/line}
443 \lineii{'stdname'}{standard name}
444 \lineii{'time'}{internal time}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000445\end{tableii}
446
447Note that all sorts on statistics are in descending order (placing
448most time consuming items first), where as name, file, and line number
Fred Drake907e76b2001-07-06 20:30:11 +0000449searches are in ascending order (alphabetical). The subtle
Fred Drake2cb824c1998-04-09 18:10:35 +0000450distinction between \code{'nfl'} and \code{'stdname'} is that the
Guido van Rossumdf804f81995-03-02 12:38:39 +0000451standard name is a sort of the name as printed, which means that the
452embedded line numbers get compared in an odd way. For example, lines
4533, 20, and 40 would (if the file names were the same) appear in the
Fred Drake2cb824c1998-04-09 18:10:35 +0000454string order 20, 3 and 40. In contrast, \code{'nfl'} does a numeric
455compare of the line numbers. In fact, \code{sort_stats('nfl')} is the
456same as \code{sort_stats('name', 'file', 'line')}.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000457
458For compatibility with the old profiler, the numeric arguments
Fred Drake2cb824c1998-04-09 18:10:35 +0000459\code{-1}, \code{0}, \code{1}, and \code{2} are permitted. They are
460interpreted as \code{'stdname'}, \code{'calls'}, \code{'time'}, and
461\code{'cumulative'} respectively. If this old style format (numeric)
Guido van Rossumdf804f81995-03-02 12:38:39 +0000462is used, only one sort key (the numeric key) will be used, and
463additional arguments will be silently ignored.
Fred Drake8fe533e1998-03-27 05:27:08 +0000464\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000465
466
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000467\begin{methoddesc}[Stats]{reverse_order}{}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000468This method for the \class{Stats} class reverses the ordering of the basic
Guido van Rossumdf804f81995-03-02 12:38:39 +0000469list within the object. This method is provided primarily for
470compatibility with the old profiler. Its utility is questionable
471now that ascending vs descending order is properly selected based on
472the sort key of choice.
Fred Drake8fe533e1998-03-27 05:27:08 +0000473\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000474
Fred Drake20006b22001-07-02 21:22:39 +0000475\begin{methoddesc}[Stats]{print_stats}{\optional{restriction, \moreargs}}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000476This method for the \class{Stats} class prints out a report as described
477in the \function{profile.run()} definition.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000478
Fred Drake8fa5eb81998-02-27 05:23:37 +0000479The order of the printing is based on the last \method{sort_stats()}
480operation done on the object (subject to caveats in \method{add()} and
Raymond Hettinger0e53d232003-07-14 18:24:26 +0000481\method{strip_dirs()}).
Guido van Rossumdf804f81995-03-02 12:38:39 +0000482
483The arguments provided (if any) can be used to limit the list down to
484the significant entries. Initially, the list is taken to be the
485complete set of profiled functions. Each restriction is either an
486integer (to select a count of lines), or a decimal fraction between
4870.0 and 1.0 inclusive (to select a percentage of lines), or a regular
Guido van Rossum364e6431997-11-18 15:28:46 +0000488expression (to pattern match the standard name that is printed; as of
489Python 1.5b1, this uses the Perl-style regular expression syntax
Fred Drakeffbe6871999-04-22 21:23:22 +0000490defined by the \refmodule{re} module). If several restrictions are
Guido van Rossum364e6431997-11-18 15:28:46 +0000491provided, then they are applied sequentially. For example:
Guido van Rossumdf804f81995-03-02 12:38:39 +0000492
Fred Drake19479911998-02-13 06:58:54 +0000493\begin{verbatim}
Fred Drake2cb824c1998-04-09 18:10:35 +0000494print_stats(.1, 'foo:')
Fred Drake19479911998-02-13 06:58:54 +0000495\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000496
Guido van Rossumdf804f81995-03-02 12:38:39 +0000497would first limit the printing to first 10\% of list, and then only
498print functions that were part of filename \samp{.*foo:}. In
499contrast, the command:
500
Fred Drake19479911998-02-13 06:58:54 +0000501\begin{verbatim}
Fred Drake2cb824c1998-04-09 18:10:35 +0000502print_stats('foo:', .1)
Fred Drake19479911998-02-13 06:58:54 +0000503\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000504
Guido van Rossumdf804f81995-03-02 12:38:39 +0000505would limit the list to all functions having file names \samp{.*foo:},
506and then proceed to only print the first 10\% of them.
Fred Drake8fe533e1998-03-27 05:27:08 +0000507\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000508
509
Fred Drake20006b22001-07-02 21:22:39 +0000510\begin{methoddesc}[Stats]{print_callers}{\optional{restriction, \moreargs}}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000511This method for the \class{Stats} class prints a list of all functions
Guido van Rossumdf804f81995-03-02 12:38:39 +0000512that called each function in the profiled database. The ordering is
Fred Drake8fa5eb81998-02-27 05:23:37 +0000513identical to that provided by \method{print_stats()}, and the definition
Guido van Rossumdf804f81995-03-02 12:38:39 +0000514of the restricting argument is also identical. For convenience, a
515number is shown in parentheses after each caller to show how many
516times this specific call was made. A second non-parenthesized number
517is the cumulative time spent in the function at the right.
Fred Drake8fe533e1998-03-27 05:27:08 +0000518\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000519
Fred Drake20006b22001-07-02 21:22:39 +0000520\begin{methoddesc}[Stats]{print_callees}{\optional{restriction, \moreargs}}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000521This method for the \class{Stats} class prints a list of all function
Guido van Rossumdf804f81995-03-02 12:38:39 +0000522that were called by the indicated function. Aside from this reversal
523of direction of calls (re: called vs was called by), the arguments and
Fred Drake8fa5eb81998-02-27 05:23:37 +0000524ordering are identical to the \method{print_callers()} method.
Fred Drake8fe533e1998-03-27 05:27:08 +0000525\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000526
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000527\begin{methoddesc}[Stats]{ignore}{}
Fred Drakeea003fc1999-04-05 21:59:15 +0000528\deprecated{1.5.1}{This is not needed in modern versions of
529Python.\footnote{
530 This was once necessary, when Python would print any unused expression
531 result that was not \code{None}. The method is still defined for
532 backward compatibility.}}
Fred Drake8fe533e1998-03-27 05:27:08 +0000533\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000534
535
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000536\section{Limitations \label{profile-limits}}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000537
538There are two fundamental limitations on this profiler. The first is
539that it relies on the Python interpreter to dispatch \dfn{call},
Fred Drake8fa5eb81998-02-27 05:23:37 +0000540\dfn{return}, and \dfn{exception} events. Compiled \C{} code does not
Guido van Rossumdf804f81995-03-02 12:38:39 +0000541get interpreted, and hence is ``invisible'' to the profiler. All time
Fred Drake3a18f3b1998-04-02 19:36:25 +0000542spent in \C{} code (including built-in functions) will be charged to the
Fred Drake8fa5eb81998-02-27 05:23:37 +0000543Python function that invoked the \C{} code. If the \C{} code calls out
Guido van Rossumdf804f81995-03-02 12:38:39 +0000544to some native Python code, then those calls will be profiled
545properly.
546
547The second limitation has to do with accuracy of timing information.
548There is a fundamental problem with deterministic profilers involving
549accuracy. The most obvious restriction is that the underlying ``clock''
550is only ticking at a rate (typically) of about .001 seconds. Hence no
Raymond Hettinger999b57c2003-08-25 04:28:05 +0000551measurements will be more accurate than the underlying clock. If
Guido van Rossumdf804f81995-03-02 12:38:39 +0000552enough measurements are taken, then the ``error'' will tend to average
553out. Unfortunately, removing this first error induces a second source
554of error...
555
556The second problem is that it ``takes a while'' from when an event is
557dispatched until the profiler's call to get the time actually
558\emph{gets} the state of the clock. Similarly, there is a certain lag
559when exiting the profiler event handler from the time that the clock's
560value was obtained (and then squirreled away), until the user's code
561is once again executing. As a result, functions that are called many
562times, or call many functions, will typically accumulate this error.
563The error that accumulates in this fashion is typically less than the
Fred Drake907e76b2001-07-06 20:30:11 +0000564accuracy of the clock (less than one clock tick), but it
Guido van Rossumdf804f81995-03-02 12:38:39 +0000565\emph{can} accumulate and become very significant. This profiler
566provides a means of calibrating itself for a given platform so that
Fred Drake907e76b2001-07-06 20:30:11 +0000567this error can be probabilistically (on the average) removed.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000568After the profiler is calibrated, it will be more accurate (in a least
569square sense), but it will sometimes produce negative numbers (when
570call counts are exceptionally low, and the gods of probability work
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000571against you :-). ) Do \emph{not} be alarmed by negative numbers in
Guido van Rossumdf804f81995-03-02 12:38:39 +0000572the profile. They should \emph{only} appear if you have calibrated
573your profiler, and the results are actually better than without
574calibration.
575
576
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000577\section{Calibration \label{profile-calibration}}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000578
Tim Peters659a6032001-10-09 20:51:19 +0000579The profiler subtracts a constant from each
Guido van Rossumdf804f81995-03-02 12:38:39 +0000580event handling time to compensate for the overhead of calling the time
Tim Peters659a6032001-10-09 20:51:19 +0000581function, and socking away the results. By default, the constant is 0.
582The following procedure can
583be used to obtain a better constant for a given platform (see discussion
Guido van Rossumdf804f81995-03-02 12:38:39 +0000584in section Limitations above).
585
Fred Drake19479911998-02-13 06:58:54 +0000586\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000587import profile
588pr = profile.Profile()
Tim Peters659a6032001-10-09 20:51:19 +0000589for i in range(5):
590 print pr.calibrate(10000)
Fred Drake19479911998-02-13 06:58:54 +0000591\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000592
Tim Peters659a6032001-10-09 20:51:19 +0000593The method executes the number of Python calls given by the argument,
594directly and again under the profiler, measuring the time for both.
595It then computes the hidden overhead per profiler event, and returns
596that as a float. For example, on an 800 MHz Pentium running
597Windows 2000, and using Python's time.clock() as the timer,
598the magical number is about 12.5e-6.
Fred Drake8fa5eb81998-02-27 05:23:37 +0000599
Guido van Rossumdf804f81995-03-02 12:38:39 +0000600The object of this exercise is to get a fairly consistent result.
Tim Peters659a6032001-10-09 20:51:19 +0000601If your computer is \emph{very} fast, or your timer function has poor
602resolution, you might have to pass 100000, or even 1000000, to get
603consistent results.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000604
Tim Peters659a6032001-10-09 20:51:19 +0000605When you have a consistent answer,
606there are three ways you can use it:\footnote{Prior to Python 2.2, it
607 was necessary to edit the profiler source code to embed the bias as
608 a literal number. You still can, but that method is no longer
609 described, because no longer needed.}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000610
Fred Drake19479911998-02-13 06:58:54 +0000611\begin{verbatim}
Tim Peters659a6032001-10-09 20:51:19 +0000612import profile
Guido van Rossume47da0a1997-07-17 16:34:52 +0000613
Tim Peters659a6032001-10-09 20:51:19 +0000614# 1. Apply computed bias to all Profile instances created hereafter.
Tim Peters8cd015c2001-10-09 20:54:23 +0000615profile.Profile.bias = your_computed_bias
Tim Peters659a6032001-10-09 20:51:19 +0000616
617# 2. Apply computed bias to a specific Profile instance.
618pr = profile.Profile()
619pr.bias = your_computed_bias
620
621# 3. Specify computed bias in instance constructor.
622pr = profile.Profile(bias=your_computed_bias)
Fred Drake19479911998-02-13 06:58:54 +0000623\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000624
Tim Peters659a6032001-10-09 20:51:19 +0000625If you have a choice, you are better off choosing a smaller constant, and
626then your results will ``less often'' show up as negative in profile
627statistics.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000628
629
Guido van Rossum86cb0921995-03-20 12:59:56 +0000630\section{Extensions --- Deriving Better Profilers}
631\nodename{Profiler Extensions}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000632
Fred Drake8fa5eb81998-02-27 05:23:37 +0000633The \class{Profile} class of module \module{profile} was written so that
Tim Peters0a1fc4e2001-10-07 03:12:08 +0000634derived classes could be developed to extend the profiler. The details
635are not described here, as doing this successfully requires an expert
636understanding of how the \class{Profile} class works internally. Study
637the source code of module \module{profile} carefully if you want to
638pursue this.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000639
Tim Peters0a1fc4e2001-10-07 03:12:08 +0000640If all you want to do is change how current time is determined (for
641example, to force use of wall-clock time or elapsed process time),
642pass the timing function you want to the \class{Profile} class
643constructor:
Guido van Rossumdf804f81995-03-02 12:38:39 +0000644
Fred Drake19479911998-02-13 06:58:54 +0000645\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000646pr = profile.Profile(your_time_func)
Fred Drake19479911998-02-13 06:58:54 +0000647\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000648
Tim Peters0a1fc4e2001-10-07 03:12:08 +0000649The resulting profiler will then call \code{your_time_func()}.
650The function should return a single number, or a list of
651numbers whose sum is the current time (like what \function{os.times()}
652returns). If the function returns a single time number, or the list of
653returned numbers has length 2, then you will get an especially fast
654version of the dispatch routine.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000655
Tim Peters0a1fc4e2001-10-07 03:12:08 +0000656Be warned that you should calibrate the profiler class for the
Guido van Rossumdf804f81995-03-02 12:38:39 +0000657timer function that you choose. For most machines, a timer that
658returns a lone integer value will provide the best results in terms of
Fred Drake8fa5eb81998-02-27 05:23:37 +0000659low overhead during profiling. (\function{os.times()} is
Tim Peters0a1fc4e2001-10-07 03:12:08 +0000660\emph{pretty} bad, as it returns a tuple of floating point values). If
661you want to substitute a better timer in the cleanest fashion,
662derive a class and hardwire a replacement dispatch method that best
Fred Drake8fa5eb81998-02-27 05:23:37 +0000663handles your timer call, along with the appropriate calibration
Fred Drake62f9d7c2001-06-08 05:04:19 +0000664constant.