blob: c283fd66c068807bd663a05dee338d48aa7df92d [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
Fred Drakefee6f332004-03-23 21:40:07 +0000107To profile an application with a main entry point of \function{foo()},
108you would add the following to your module:
Guido van Rossumdf804f81995-03-02 12:38:39 +0000109
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
Fred Drakefee6f332004-03-23 21:40:07 +0000115The above action would cause \function{foo()} to be run, and a series of
Guido van Rossumdf804f81995-03-02 12:38:39 +0000116informative 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
Fred Drakefee6f332004-03-23 21:40:07 +0000140\programopt{-s} only applies to standard output (\programopt{-o} is
141not supplied). Look in the \class{Stats} documentation for valid sort
142values.
Nicholas Bastin824b1b22004-03-23 18:44:39 +0000143
Guido van Rossumdf804f81995-03-02 12:38:39 +0000144When you wish to review the profile, you should use the methods in the
Fred Drake8fa5eb81998-02-27 05:23:37 +0000145\module{pstats} module. Typically you would load the statistics data as
Guido van Rossumdf804f81995-03-02 12:38:39 +0000146follows:
147
Fred Drake19479911998-02-13 06:58:54 +0000148\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000149import pstats
150p = pstats.Stats('fooprof')
Fred Drake19479911998-02-13 06:58:54 +0000151\end{verbatim}
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000152
Fred Drake8fa5eb81998-02-27 05:23:37 +0000153The class \class{Stats} (the above code just created an instance of
Guido van Rossumdf804f81995-03-02 12:38:39 +0000154this class) has a variety of methods for manipulating and printing the
Fred Drakefee6f332004-03-23 21:40:07 +0000155data that was just read into \code{p}. When you ran
Fred Drake8fa5eb81998-02-27 05:23:37 +0000156\function{profile.run()} above, what was printed was the result of three
Guido van Rossumdf804f81995-03-02 12:38:39 +0000157method calls:
158
Fred Drake19479911998-02-13 06:58:54 +0000159\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000160p.strip_dirs().sort_stats(-1).print_stats()
Fred Drake19479911998-02-13 06:58:54 +0000161\end{verbatim}
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000162
Guido van Rossumdf804f81995-03-02 12:38:39 +0000163The first method removed the extraneous path from all the module
164names. The second method sorted all the entries according to the
165standard module/line/name string that is printed (this is to comply
166with the semantics of the old profiler). The third method printed out
167all the statistics. You might try the following sort calls:
168
Fred Drake19479911998-02-13 06:58:54 +0000169\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000170p.sort_stats('name')
171p.print_stats()
Fred Drake19479911998-02-13 06:58:54 +0000172\end{verbatim}
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000173
Guido van Rossumdf804f81995-03-02 12:38:39 +0000174The first call will actually sort the list by function name, and the
175second call will print out the statistics. The following are some
176interesting calls to experiment with:
177
Fred Drake19479911998-02-13 06:58:54 +0000178\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000179p.sort_stats('cumulative').print_stats(10)
Fred Drake19479911998-02-13 06:58:54 +0000180\end{verbatim}
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000181
Guido van Rossumdf804f81995-03-02 12:38:39 +0000182This sorts the profile by cumulative time in a function, and then only
183prints the ten most significant lines. If you want to understand what
184algorithms are taking time, the above line is what you would use.
185
186If you were looking to see what functions were looping a lot, and
187taking a lot of time, you would do:
188
Fred Drake19479911998-02-13 06:58:54 +0000189\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000190p.sort_stats('time').print_stats(10)
Fred Drake19479911998-02-13 06:58:54 +0000191\end{verbatim}
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000192
Guido van Rossumdf804f81995-03-02 12:38:39 +0000193to sort according to time spent within each function, and then print
194the statistics for the top ten functions.
195
196You might also try:
197
Fred Drake19479911998-02-13 06:58:54 +0000198\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000199p.sort_stats('file').print_stats('__init__')
Fred Drake19479911998-02-13 06:58:54 +0000200\end{verbatim}
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000201
Guido van Rossumdf804f81995-03-02 12:38:39 +0000202This will sort all the statistics by file name, and then print out
Fred Drakefee6f332004-03-23 21:40:07 +0000203statistics for only the class init methods (since they are spelled
204with \code{__init__} in them). As one final example, you could try:
Guido van Rossumdf804f81995-03-02 12:38:39 +0000205
Fred Drake19479911998-02-13 06:58:54 +0000206\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000207p.sort_stats('time', 'cum').print_stats(.5, 'init')
Fred Drake19479911998-02-13 06:58:54 +0000208\end{verbatim}
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000209
Guido van Rossumdf804f81995-03-02 12:38:39 +0000210This line sorts statistics with a primary key of time, and a secondary
211key of cumulative time, and then prints out some of the statistics.
212To be specific, the list is first culled down to 50\% (re: \samp{.5})
213of its original size, then only lines containing \code{init} are
214maintained, and that sub-sub-list is printed.
215
216If you wondered what functions called the above functions, you could
Fred Drakefee6f332004-03-23 21:40:07 +0000217now (\code{p} is still sorted according to the last criteria) do:
Guido van Rossumdf804f81995-03-02 12:38:39 +0000218
Fred Drake19479911998-02-13 06:58:54 +0000219\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000220p.print_callers(.5, 'init')
Fred Drake19479911998-02-13 06:58:54 +0000221\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000222
Tim Peters0a1fc4e2001-10-07 03:12:08 +0000223and you would get a list of callers for each of the listed functions.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000224
225If you want more functionality, you're going to have to read the
226manual, or guess what the following functions do:
227
Fred Drake19479911998-02-13 06:58:54 +0000228\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000229p.print_callees()
230p.add('fooprof')
Fred Drake19479911998-02-13 06:58:54 +0000231\end{verbatim}
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000232
Eric S. Raymond4f3980d2001-04-13 00:23:01 +0000233Invoked as a script, the \module{pstats} module is a statistics
234browser for reading and examining profile dumps. It has a simple
Fred Drakea3e56a62001-04-13 14:34:58 +0000235line-oriented interface (implemented using \refmodule{cmd}) and
Eric S. Raymond4f3980d2001-04-13 00:23:01 +0000236interactive help.
237
Guido van Rossumdf804f81995-03-02 12:38:39 +0000238\section{What Is Deterministic Profiling?}
Guido van Rossum86cb0921995-03-20 12:59:56 +0000239\nodename{Deterministic Profiling}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000240
241\dfn{Deterministic profiling} is meant to reflect the fact that all
Fred Drakea3e56a62001-04-13 14:34:58 +0000242\emph{function call}, \emph{function return}, and \emph{exception} events
Guido van Rossumdf804f81995-03-02 12:38:39 +0000243are monitored, and precise timings are made for the intervals between
244these events (during which time the user's code is executing). In
245contrast, \dfn{statistical profiling} (which is not done by this
246module) randomly samples the effective instruction pointer, and
247deduces where time is being spent. The latter technique traditionally
248involves less overhead (as the code does not need to be instrumented),
249but provides only relative indications of where time is being spent.
250
251In Python, since there is an interpreter active during execution, the
252presence of instrumented code is not required to do deterministic
253profiling. Python automatically provides a \dfn{hook} (optional
254callback) for each event. In addition, the interpreted nature of
255Python tends to add so much overhead to execution, that deterministic
256profiling tends to only add small processing overhead in typical
257applications. The result is that deterministic profiling is not that
258expensive, yet provides extensive run time statistics about the
259execution of a Python program.
260
261Call count statistics can be used to identify bugs in code (surprising
262counts), and to identify possible inline-expansion points (high call
263counts). Internal time statistics can be used to identify ``hot
264loops'' that should be carefully optimized. Cumulative time
265statistics should be used to identify high level errors in the
266selection of algorithms. Note that the unusual handling of cumulative
267times in this profiler allows statistics for recursive implementations
268of algorithms to be directly compared to iterative implementations.
269
270
271\section{Reference Manual}
Fred Drakeb91e9341998-07-23 17:59:49 +0000272
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000273\declaremodule{standard}{profile}
274\modulesynopsis{Python profiler}
Fred Drakeb91e9341998-07-23 17:59:49 +0000275
Guido van Rossumdf804f81995-03-02 12:38:39 +0000276
Guido van Rossumdf804f81995-03-02 12:38:39 +0000277
278The primary entry point for the profiler is the global function
Fred Drake8fa5eb81998-02-27 05:23:37 +0000279\function{profile.run()}. It is typically used to create any profile
Guido van Rossumdf804f81995-03-02 12:38:39 +0000280information. The reports are formatted and printed using methods of
Fred Drake8fa5eb81998-02-27 05:23:37 +0000281the class \class{pstats.Stats}. The following is a description of all
Guido van Rossumdf804f81995-03-02 12:38:39 +0000282of these standard entry points and functions. For a more in-depth
283view of some of the code, consider reading the later section on
284Profiler Extensions, which includes discussion of how to derive
285``better'' profilers from the classes presented, or reading the source
286code for these modules.
287
Nicholas Bastin1eb4bfc2004-03-22 20:12:56 +0000288\begin{funcdesc}{run}{command\optional{, filename}}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000289
290This function takes a single argument that has can be passed to the
Fred Drake8fa5eb81998-02-27 05:23:37 +0000291\keyword{exec} statement, and an optional file name. In all cases this
292routine attempts to \keyword{exec} its first argument, and gather profiling
Guido van Rossumdf804f81995-03-02 12:38:39 +0000293statistics from the execution. If no file name is present, then this
294function automatically prints a simple profiling report, sorted by the
295standard name string (file/line/function-name) that is presented in
296each line. The following is a typical output from such a call:
297
Fred Drake19479911998-02-13 06:58:54 +0000298\begin{verbatim}
Guido van Rossum96628a91995-04-10 11:34:00 +0000299 main()
300 2706 function calls (2004 primitive calls) in 4.504 CPU seconds
Guido van Rossumdf804f81995-03-02 12:38:39 +0000301
Guido van Rossum96628a91995-04-10 11:34:00 +0000302Ordered by: standard name
Guido van Rossumdf804f81995-03-02 12:38:39 +0000303
Guido van Rossum96628a91995-04-10 11:34:00 +0000304ncalls tottime percall cumtime percall filename:lineno(function)
305 2 0.006 0.003 0.953 0.477 pobject.py:75(save_objects)
306 43/3 0.533 0.012 0.749 0.250 pobject.py:99(evaluate)
307 ...
Fred Drake19479911998-02-13 06:58:54 +0000308\end{verbatim}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000309
310The first line indicates that this profile was generated by the call:\\
311\code{profile.run('main()')}, and hence the exec'ed string is
312\code{'main()'}. The second line indicates that 2706 calls were
313monitored. Of those calls, 2004 were \dfn{primitive}. We define
314\dfn{primitive} to mean that the call was not induced via recursion.
315The next line: \code{Ordered by:\ standard name}, indicates that
316the text string in the far right column was used to sort the output.
317The column headings include:
318
319\begin{description}
320
321\item[ncalls ]
Tim Peters0a1fc4e2001-10-07 03:12:08 +0000322for the number of calls,
Guido van Rossumdf804f81995-03-02 12:38:39 +0000323
324\item[tottime ]
325for the total time spent in the given function (and excluding time
326made in calls to sub-functions),
327
328\item[percall ]
329is the quotient of \code{tottime} divided by \code{ncalls}
330
331\item[cumtime ]
Fred Drake907e76b2001-07-06 20:30:11 +0000332is the total time spent in this and all subfunctions (from invocation
333till exit). This figure is accurate \emph{even} for recursive
Guido van Rossumdf804f81995-03-02 12:38:39 +0000334functions.
335
336\item[percall ]
337is the quotient of \code{cumtime} divided by primitive calls
338
339\item[filename:lineno(function) ]
340provides the respective data of each function
341
342\end{description}
343
Fred Drake907e76b2001-07-06 20:30:11 +0000344When there are two numbers in the first column (for example,
345\samp{43/3}), then the latter is the number of primitive calls, and
346the former is the actual number of calls. Note that when the function
347does not recurse, these two values are the same, and only the single
348figure is printed.
Guido van Rossum96628a91995-04-10 11:34:00 +0000349
Guido van Rossumdf804f81995-03-02 12:38:39 +0000350\end{funcdesc}
351
Nicholas Bastin1eb4bfc2004-03-22 20:12:56 +0000352\begin{funcdesc}{runctx}{command, globals, locals\optional{, filename}}
353This function is similar to \function{profile.run()}, with added
354arguments to supply the globals and locals dictionaries for the
355\var{command} string.
356\end{funcdesc}
357
Fred Drake8fa5eb81998-02-27 05:23:37 +0000358Analysis of the profiler data is done using this class from the
359\module{pstats} module:
360
Fred Drake8fe533e1998-03-27 05:27:08 +0000361% now switch modules....
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000362% (This \stmodindex use may be hard to change ;-( )
Fred Drake8fe533e1998-03-27 05:27:08 +0000363\stmodindex{pstats}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000364
Fred Drakee05c3e02004-03-23 20:30:59 +0000365\begin{classdesc}{Stats}{filename\optional{, \moreargs}}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000366This class constructor creates an instance of a ``statistics object''
Fred Drake8fa5eb81998-02-27 05:23:37 +0000367from a \var{filename} (or set of filenames). \class{Stats} objects are
Guido van Rossumdf804f81995-03-02 12:38:39 +0000368manipulated by methods, in order to print useful reports.
369
370The file selected by the above constructor must have been created by
Fred Drake8fa5eb81998-02-27 05:23:37 +0000371the corresponding version of \module{profile}. To be specific, there is
372\emph{no} file compatibility guaranteed with future versions of this
Guido van Rossumdf804f81995-03-02 12:38:39 +0000373profiler, and there is no compatibility with files produced by other
Fred Drake907e76b2001-07-06 20:30:11 +0000374profilers (such as the old system profiler).
Guido van Rossumdf804f81995-03-02 12:38:39 +0000375
376If several files are provided, all the statistics for identical
377functions will be coalesced, so that an overall view of several
378processes can be considered in a single report. If additional files
Fred Drake8fa5eb81998-02-27 05:23:37 +0000379need to be combined with data in an existing \class{Stats} object, the
380\method{add()} method can be used.
381\end{classdesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000382
383
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000384\subsection{The \class{Stats} Class \label{profile-stats}}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000385
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000386\class{Stats} objects have the following methods:
Guido van Rossumdf804f81995-03-02 12:38:39 +0000387
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000388\begin{methoddesc}[Stats]{strip_dirs}{}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000389This method for the \class{Stats} class removes all leading path
390information from file names. It is very useful in reducing the size
391of the printout to fit within (close to) 80 columns. This method
392modifies the object, and the stripped information is lost. After
393performing a strip operation, the object is considered to have its
394entries in a ``random'' order, as it was just after object
395initialization and loading. If \method{strip_dirs()} causes two
Fred Drake907e76b2001-07-06 20:30:11 +0000396function names to be indistinguishable (they are on the same
Fred Drake8fa5eb81998-02-27 05:23:37 +0000397line of the same filename, and have the same function name), then the
398statistics for these two entries are accumulated into a single entry.
Fred Drake8fe533e1998-03-27 05:27:08 +0000399\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000400
401
Fred Drakee05c3e02004-03-23 20:30:59 +0000402\begin{methoddesc}[Stats]{add}{filename\optional{, \moreargs}}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000403This method of the \class{Stats} class accumulates additional
404profiling information into the current profiling object. Its
405arguments should refer to filenames created by the corresponding
406version of \function{profile.run()}. Statistics for identically named
407(re: file, line, name) functions are automatically accumulated into
408single function statistics.
Fred Drake8fe533e1998-03-27 05:27:08 +0000409\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000410
Fred Drake126d3662003-05-14 14:29:27 +0000411\begin{methoddesc}[Stats]{dump_stats}{filename}
412Save the data loaded into the \class{Stats} object to a file named
413\var{filename}. The file is created if it does not exist, and is
414overwritten if it already exists. This is equivalent to the method of
415the same name on the \class{profile.Profile} class.
416\versionadded{2.3}
417\end{methoddesc}
418
Fred Drakee05c3e02004-03-23 20:30:59 +0000419\begin{methoddesc}[Stats]{sort_stats}{key\optional{, \moreargs}}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000420This method modifies the \class{Stats} object by sorting it according
421to the supplied criteria. The argument is typically a string
Fred Drake2cb824c1998-04-09 18:10:35 +0000422identifying the basis of a sort (example: \code{'time'} or
423\code{'name'}).
Guido van Rossumdf804f81995-03-02 12:38:39 +0000424
425When more than one key is provided, then additional keys are used as
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000426secondary criteria when there is equality in all keys selected
Fred Drakefee6f332004-03-23 21:40:07 +0000427before them. For example, \code{sort_stats('name', 'file')} will sort
Fred Drake8fa5eb81998-02-27 05:23:37 +0000428all the entries according to their function name, and resolve all ties
Guido van Rossumdf804f81995-03-02 12:38:39 +0000429(identical function names) by sorting by file name.
430
431Abbreviations can be used for any key names, as long as the
432abbreviation is unambiguous. The following are the keys currently
Tim Peters0a1fc4e2001-10-07 03:12:08 +0000433defined:
Guido van Rossumdf804f81995-03-02 12:38:39 +0000434
Fred Drakeee601911998-04-11 20:53:03 +0000435\begin{tableii}{l|l}{code}{Valid Arg}{Meaning}
Fred Drake5dabeed1998-04-03 07:02:35 +0000436 \lineii{'calls'}{call count}
437 \lineii{'cumulative'}{cumulative time}
438 \lineii{'file'}{file name}
439 \lineii{'module'}{file name}
440 \lineii{'pcalls'}{primitive call count}
441 \lineii{'line'}{line number}
442 \lineii{'name'}{function name}
443 \lineii{'nfl'}{name/file/line}
444 \lineii{'stdname'}{standard name}
445 \lineii{'time'}{internal time}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000446\end{tableii}
447
448Note that all sorts on statistics are in descending order (placing
449most time consuming items first), where as name, file, and line number
Fred Drake907e76b2001-07-06 20:30:11 +0000450searches are in ascending order (alphabetical). The subtle
Fred Drake2cb824c1998-04-09 18:10:35 +0000451distinction between \code{'nfl'} and \code{'stdname'} is that the
Guido van Rossumdf804f81995-03-02 12:38:39 +0000452standard name is a sort of the name as printed, which means that the
453embedded line numbers get compared in an odd way. For example, lines
4543, 20, and 40 would (if the file names were the same) appear in the
Fred Drake2cb824c1998-04-09 18:10:35 +0000455string order 20, 3 and 40. In contrast, \code{'nfl'} does a numeric
456compare of the line numbers. In fact, \code{sort_stats('nfl')} is the
457same as \code{sort_stats('name', 'file', 'line')}.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000458
459For compatibility with the old profiler, the numeric arguments
Fred Drake2cb824c1998-04-09 18:10:35 +0000460\code{-1}, \code{0}, \code{1}, and \code{2} are permitted. They are
461interpreted as \code{'stdname'}, \code{'calls'}, \code{'time'}, and
462\code{'cumulative'} respectively. If this old style format (numeric)
Guido van Rossumdf804f81995-03-02 12:38:39 +0000463is used, only one sort key (the numeric key) will be used, and
464additional arguments will be silently ignored.
Fred Drake8fe533e1998-03-27 05:27:08 +0000465\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000466
467
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000468\begin{methoddesc}[Stats]{reverse_order}{}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000469This method for the \class{Stats} class reverses the ordering of the basic
Guido van Rossumdf804f81995-03-02 12:38:39 +0000470list within the object. This method is provided primarily for
471compatibility with the old profiler. Its utility is questionable
472now that ascending vs descending order is properly selected based on
473the sort key of choice.
Fred Drake8fe533e1998-03-27 05:27:08 +0000474\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000475
Fred Drake20006b22001-07-02 21:22:39 +0000476\begin{methoddesc}[Stats]{print_stats}{\optional{restriction, \moreargs}}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000477This method for the \class{Stats} class prints out a report as described
478in the \function{profile.run()} definition.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000479
Fred Drake8fa5eb81998-02-27 05:23:37 +0000480The order of the printing is based on the last \method{sort_stats()}
481operation done on the object (subject to caveats in \method{add()} and
Raymond Hettinger0e53d232003-07-14 18:24:26 +0000482\method{strip_dirs()}).
Guido van Rossumdf804f81995-03-02 12:38:39 +0000483
484The arguments provided (if any) can be used to limit the list down to
485the significant entries. Initially, the list is taken to be the
486complete set of profiled functions. Each restriction is either an
487integer (to select a count of lines), or a decimal fraction between
4880.0 and 1.0 inclusive (to select a percentage of lines), or a regular
Guido van Rossum364e6431997-11-18 15:28:46 +0000489expression (to pattern match the standard name that is printed; as of
490Python 1.5b1, this uses the Perl-style regular expression syntax
Fred Drakeffbe6871999-04-22 21:23:22 +0000491defined by the \refmodule{re} module). If several restrictions are
Guido van Rossum364e6431997-11-18 15:28:46 +0000492provided, then they are applied sequentially. For example:
Guido van Rossumdf804f81995-03-02 12:38:39 +0000493
Fred Drake19479911998-02-13 06:58:54 +0000494\begin{verbatim}
Fred Drake2cb824c1998-04-09 18:10:35 +0000495print_stats(.1, 'foo:')
Fred Drake19479911998-02-13 06:58:54 +0000496\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000497
Guido van Rossumdf804f81995-03-02 12:38:39 +0000498would first limit the printing to first 10\% of list, and then only
Fred Drakefee6f332004-03-23 21:40:07 +0000499print functions that were part of filename \file{.*foo:}. In
Guido van Rossumdf804f81995-03-02 12:38:39 +0000500contrast, the command:
501
Fred Drake19479911998-02-13 06:58:54 +0000502\begin{verbatim}
Fred Drake2cb824c1998-04-09 18:10:35 +0000503print_stats('foo:', .1)
Fred Drake19479911998-02-13 06:58:54 +0000504\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000505
Fred Drakefee6f332004-03-23 21:40:07 +0000506would limit the list to all functions having file names \file{.*foo:},
Guido van Rossumdf804f81995-03-02 12:38:39 +0000507and then proceed to only print the first 10\% of them.
Fred Drake8fe533e1998-03-27 05:27:08 +0000508\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000509
510
Fred Drake20006b22001-07-02 21:22:39 +0000511\begin{methoddesc}[Stats]{print_callers}{\optional{restriction, \moreargs}}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000512This method for the \class{Stats} class prints a list of all functions
Guido van Rossumdf804f81995-03-02 12:38:39 +0000513that called each function in the profiled database. The ordering is
Fred Drake8fa5eb81998-02-27 05:23:37 +0000514identical to that provided by \method{print_stats()}, and the definition
Guido van Rossumdf804f81995-03-02 12:38:39 +0000515of the restricting argument is also identical. For convenience, a
516number is shown in parentheses after each caller to show how many
517times this specific call was made. A second non-parenthesized number
518is the cumulative time spent in the function at the right.
Fred Drake8fe533e1998-03-27 05:27:08 +0000519\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000520
Fred Drake20006b22001-07-02 21:22:39 +0000521\begin{methoddesc}[Stats]{print_callees}{\optional{restriction, \moreargs}}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000522This method for the \class{Stats} class prints a list of all function
Guido van Rossumdf804f81995-03-02 12:38:39 +0000523that were called by the indicated function. Aside from this reversal
524of direction of calls (re: called vs was called by), the arguments and
Fred Drake8fa5eb81998-02-27 05:23:37 +0000525ordering are identical to the \method{print_callers()} method.
Fred Drake8fe533e1998-03-27 05:27:08 +0000526\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000527
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000528\begin{methoddesc}[Stats]{ignore}{}
Fred Drakeea003fc1999-04-05 21:59:15 +0000529\deprecated{1.5.1}{This is not needed in modern versions of
530Python.\footnote{
531 This was once necessary, when Python would print any unused expression
532 result that was not \code{None}. The method is still defined for
533 backward compatibility.}}
Fred Drake8fe533e1998-03-27 05:27:08 +0000534\end{methoddesc}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000535
536
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000537\section{Limitations \label{profile-limits}}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000538
539There are two fundamental limitations on this profiler. The first is
540that it relies on the Python interpreter to dispatch \dfn{call},
Fred Drake8fa5eb81998-02-27 05:23:37 +0000541\dfn{return}, and \dfn{exception} events. Compiled \C{} code does not
Guido van Rossumdf804f81995-03-02 12:38:39 +0000542get interpreted, and hence is ``invisible'' to the profiler. All time
Fred Drake3a18f3b1998-04-02 19:36:25 +0000543spent in \C{} code (including built-in functions) will be charged to the
Fred Drake8fa5eb81998-02-27 05:23:37 +0000544Python function that invoked the \C{} code. If the \C{} code calls out
Guido van Rossumdf804f81995-03-02 12:38:39 +0000545to some native Python code, then those calls will be profiled
546properly.
547
548The second limitation has to do with accuracy of timing information.
549There is a fundamental problem with deterministic profilers involving
550accuracy. The most obvious restriction is that the underlying ``clock''
551is only ticking at a rate (typically) of about .001 seconds. Hence no
Raymond Hettinger999b57c2003-08-25 04:28:05 +0000552measurements will be more accurate than the underlying clock. If
Guido van Rossumdf804f81995-03-02 12:38:39 +0000553enough measurements are taken, then the ``error'' will tend to average
554out. Unfortunately, removing this first error induces a second source
Fred Drakee05c3e02004-03-23 20:30:59 +0000555of error.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000556
557The second problem is that it ``takes a while'' from when an event is
558dispatched until the profiler's call to get the time actually
559\emph{gets} the state of the clock. Similarly, there is a certain lag
560when exiting the profiler event handler from the time that the clock's
561value was obtained (and then squirreled away), until the user's code
562is once again executing. As a result, functions that are called many
563times, or call many functions, will typically accumulate this error.
564The error that accumulates in this fashion is typically less than the
Fred Drake907e76b2001-07-06 20:30:11 +0000565accuracy of the clock (less than one clock tick), but it
Guido van Rossumdf804f81995-03-02 12:38:39 +0000566\emph{can} accumulate and become very significant. This profiler
567provides a means of calibrating itself for a given platform so that
Fred Drake907e76b2001-07-06 20:30:11 +0000568this error can be probabilistically (on the average) removed.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000569After the profiler is calibrated, it will be more accurate (in a least
570square sense), but it will sometimes produce negative numbers (when
571call counts are exceptionally low, and the gods of probability work
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000572against you :-). ) Do \emph{not} be alarmed by negative numbers in
Guido van Rossumdf804f81995-03-02 12:38:39 +0000573the profile. They should \emph{only} appear if you have calibrated
574your profiler, and the results are actually better than without
575calibration.
576
577
Fred Drakeb9f1f6d1999-04-21 21:43:17 +0000578\section{Calibration \label{profile-calibration}}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000579
Tim Peters659a6032001-10-09 20:51:19 +0000580The profiler subtracts a constant from each
Guido van Rossumdf804f81995-03-02 12:38:39 +0000581event handling time to compensate for the overhead of calling the time
Tim Peters659a6032001-10-09 20:51:19 +0000582function, and socking away the results. By default, the constant is 0.
583The following procedure can
584be used to obtain a better constant for a given platform (see discussion
Guido van Rossumdf804f81995-03-02 12:38:39 +0000585in section Limitations above).
586
Fred Drake19479911998-02-13 06:58:54 +0000587\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000588import profile
589pr = profile.Profile()
Tim Peters659a6032001-10-09 20:51:19 +0000590for i in range(5):
591 print pr.calibrate(10000)
Fred Drake19479911998-02-13 06:58:54 +0000592\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000593
Tim Peters659a6032001-10-09 20:51:19 +0000594The method executes the number of Python calls given by the argument,
595directly and again under the profiler, measuring the time for both.
596It then computes the hidden overhead per profiler event, and returns
597that as a float. For example, on an 800 MHz Pentium running
598Windows 2000, and using Python's time.clock() as the timer,
599the magical number is about 12.5e-6.
Fred Drake8fa5eb81998-02-27 05:23:37 +0000600
Guido van Rossumdf804f81995-03-02 12:38:39 +0000601The object of this exercise is to get a fairly consistent result.
Tim Peters659a6032001-10-09 20:51:19 +0000602If your computer is \emph{very} fast, or your timer function has poor
603resolution, you might have to pass 100000, or even 1000000, to get
604consistent results.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000605
Tim Peters659a6032001-10-09 20:51:19 +0000606When you have a consistent answer,
607there are three ways you can use it:\footnote{Prior to Python 2.2, it
608 was necessary to edit the profiler source code to embed the bias as
609 a literal number. You still can, but that method is no longer
610 described, because no longer needed.}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000611
Fred Drake19479911998-02-13 06:58:54 +0000612\begin{verbatim}
Tim Peters659a6032001-10-09 20:51:19 +0000613import profile
Guido van Rossume47da0a1997-07-17 16:34:52 +0000614
Tim Peters659a6032001-10-09 20:51:19 +0000615# 1. Apply computed bias to all Profile instances created hereafter.
Tim Peters8cd015c2001-10-09 20:54:23 +0000616profile.Profile.bias = your_computed_bias
Tim Peters659a6032001-10-09 20:51:19 +0000617
618# 2. Apply computed bias to a specific Profile instance.
619pr = profile.Profile()
620pr.bias = your_computed_bias
621
622# 3. Specify computed bias in instance constructor.
623pr = profile.Profile(bias=your_computed_bias)
Fred Drake19479911998-02-13 06:58:54 +0000624\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000625
Tim Peters659a6032001-10-09 20:51:19 +0000626If you have a choice, you are better off choosing a smaller constant, and
627then your results will ``less often'' show up as negative in profile
628statistics.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000629
630
Guido van Rossum86cb0921995-03-20 12:59:56 +0000631\section{Extensions --- Deriving Better Profilers}
632\nodename{Profiler Extensions}
Guido van Rossumdf804f81995-03-02 12:38:39 +0000633
Fred Drake8fa5eb81998-02-27 05:23:37 +0000634The \class{Profile} class of module \module{profile} was written so that
Tim Peters0a1fc4e2001-10-07 03:12:08 +0000635derived classes could be developed to extend the profiler. The details
636are not described here, as doing this successfully requires an expert
637understanding of how the \class{Profile} class works internally. Study
638the source code of module \module{profile} carefully if you want to
639pursue this.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000640
Tim Peters0a1fc4e2001-10-07 03:12:08 +0000641If all you want to do is change how current time is determined (for
642example, to force use of wall-clock time or elapsed process time),
643pass the timing function you want to the \class{Profile} class
644constructor:
Guido van Rossumdf804f81995-03-02 12:38:39 +0000645
Fred Drake19479911998-02-13 06:58:54 +0000646\begin{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000647pr = profile.Profile(your_time_func)
Fred Drake19479911998-02-13 06:58:54 +0000648\end{verbatim}
Fred Drake8fa5eb81998-02-27 05:23:37 +0000649
Tim Peters0a1fc4e2001-10-07 03:12:08 +0000650The resulting profiler will then call \code{your_time_func()}.
651The function should return a single number, or a list of
652numbers whose sum is the current time (like what \function{os.times()}
653returns). If the function returns a single time number, or the list of
654returned numbers has length 2, then you will get an especially fast
655version of the dispatch routine.
Guido van Rossumdf804f81995-03-02 12:38:39 +0000656
Tim Peters0a1fc4e2001-10-07 03:12:08 +0000657Be warned that you should calibrate the profiler class for the
Guido van Rossumdf804f81995-03-02 12:38:39 +0000658timer function that you choose. For most machines, a timer that
659returns a lone integer value will provide the best results in terms of
Fred Drake8fa5eb81998-02-27 05:23:37 +0000660low overhead during profiling. (\function{os.times()} is
Tim Peters0a1fc4e2001-10-07 03:12:08 +0000661\emph{pretty} bad, as it returns a tuple of floating point values). If
662you want to substitute a better timer in the cleanest fashion,
663derive a class and hardwire a replacement dispatch method that best
Fred Drake8fa5eb81998-02-27 05:23:37 +0000664handles your timer call, along with the appropriate calibration
Fred Drake62f9d7c2001-06-08 05:04:19 +0000665constant.