rest25/library/profile.rst => rest262/library/profile.rst
27
28INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
29INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT
30SHALL INFOSEEK CORPORATION BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
31DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
32WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
33OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
34
n35-The profiler was written after only programming in Python for 3 weeks. As a
n35+.. _profiler-introduction:
36-result, it is probably clumsy code, but I don't know for sure yet 'cause I'm a
37-beginner :-).  I did work hard to make the code run fast, so that profiling
38-would be a reasonable thing to do.  I tried not to repeat code fragments, but
39-I'm sure I did some stuff in really awkward ways at times.  Please send
40-suggestions for improvements to: jar@netscape.com.  I won't promise *any*
41-support.  ...but I'd appreciate the feedback.
42- 
43
44Introduction to the profilers
45=============================
n46- 
47-.. _profiler introduction:
48
49.. index::
50   single: deterministic profiling
51   single: profiling, deterministic
52
n53-A :dfn:`profiler` is a program that describes the run time performance of a
n44+A :dfn:`profiler` is a program that describes the run time performance
54-program, providing a variety of statistics.  This documentation describes the
45+of a program, providing a variety of statistics.  This documentation
55-profiler functionality provided in the modules :mod:`profile` and :mod:`pstats`.
46+describes the profiler functionality provided in the modules
47+:mod:`cProfile`, :mod:`profile` and :mod:`pstats`.  This profiler
56-This profiler provides :dfn:`deterministic profiling` of any Python programs.
48+provides :dfn:`deterministic profiling` of Python programs.  It also
57-It also provides a series of report generation tools to allow users to rapidly
49+provides a series of report generation tools to allow users to rapidly
58examine the results of a profile operation.
59
60The Python standard library provides three different profilers:
61
n62-#. :mod:`profile`, a pure Python module, described in the sequel. Copyright ©
n54+#. :mod:`cProfile` is recommended for most users; it's a C extension
55+   with reasonable overhead
56+   that makes it suitable for profiling long-running programs.
57+   Based on :mod:`lsprof`,
58+   contributed by Brett Rosen and Ted Czotter.
59+ 
60+   .. versionadded:: 2.5
61+ 
62+#. :mod:`profile`, a pure Python module whose interface is imitated by
63+   :mod:`cProfile`.  Adds significant overhead to profiled programs.
64+   If you're trying to extend
65+   the profiler in some way, the task might be easier with this module.
63-   1994, by InfoSeek Corporation.
66+   Copyright © 1994, by InfoSeek Corporation.
64
65   .. versionchanged:: 2.4
n66-      also reports the time spent in calls to built-in functions and methods.
n69+      Now also reports the time spent in calls to built-in functions and methods.
67
n68-#. :mod:`cProfile`, a module written in C, with a reasonable overhead that makes
n71+#. :mod:`hotshot` was an experimental C module that focused on minimizing
69-   it suitable for profiling long-running programs. Based on :mod:`lsprof`,
72+   the overhead of profiling, at the expense of longer data
70-   contributed by Brett Rosen and Ted Czotter.
73+   post-processing times.  It is no longer maintained and may be
74+   dropped in a future version of Python.
71
n72-   .. versionadded:: 2.5
73- 
74-#. :mod:`hotshot`, a C module focusing on minimizing the overhead while
75-   profiling, at the expense of long data post-processing times.
76
77   .. versionchanged:: 2.5
n78-      the results should be more meaningful than in the past: the timing core
n78+      The results should be more meaningful than in the past: the timing core
79      contained a critical bug.
80
81The :mod:`profile` and :mod:`cProfile` modules export the same interface, so
n82-they are mostly interchangeables; :mod:`cProfile` has a much lower overhead but
n82+they are mostly interchangeable; :mod:`cProfile` has a much lower overhead but
83-is not so far as well-tested and might not be available on all systems.
83+is newer and might not be available on all systems.
84:mod:`cProfile` is really a compatibility layer on top of the internal
n85-:mod:`_lsprof` module.  The :mod:`hotshot` module is reserved to specialized
n85+:mod:`_lsprof` module.  The :mod:`hotshot` module is reserved for specialized
86-usages.
86+usage.
87- 
88-.. % \section{How Is This Profiler Different From The Old Profiler?}
89-.. % \nodename{Profiler Changes}
90-.. % 
91-.. % (This section is of historical importance only; the old profiler
92-.. % discussed here was last seen in Python 1.1.)
93-.. % 
94-.. % The big changes from old profiling module are that you get more
95-.. % information, and you pay less CPU time.  It's not a trade-off, it's a
96-.. % trade-up.
97-.. % 
98-.. % To be specific:
99-.. % 
100-.. % \begin{description}
101-.. % 
102-.. % \item[Bugs removed:]
103-.. % Local stack frame is no longer molested, execution time is now charged
104-.. % to correct functions.
105-.. % 
106-.. % \item[Accuracy increased:]
107-.. % Profiler execution time is no longer charged to user's code,
108-.. % calibration for platform is supported, file reads are not done \emph{by}
109-.. % profiler \emph{during} profiling (and charged to user's code!).
110-.. % 
111-.. % \item[Speed increased:]
112-.. % Overhead CPU cost was reduced by more than a factor of two (perhaps a
113-.. % factor of five), lightweight profiler module is all that must be
114-.. % loaded, and the report generating module (\module{pstats}) is not needed
115-.. % during profiling.
116-.. % 
117-.. % \item[Recursive functions support:]
118-.. % Cumulative times in recursive functions are correctly calculated;
119-.. % recursive entries are counted.
120-.. % 
121-.. % \item[Large growth in report generating UI:]
122-.. % Distinct profiles runs can be added together forming a comprehensive
123-.. % report; functions that import statistics take arbitrary lists of
124-.. % files; sorting criteria is now based on keywords (instead of 4 integer
125-.. % options); reports shows what functions were profiled as well as what
126-.. % profile file was referenced; output format has been improved.
127-.. % 
128-.. % \end{description}
129
130
131.. _profile-instant:
132
133Instant User's Manual
134=====================
135
136This section is provided for users that "don't want to read the manual." It
180
181   p.strip_dirs().sort_stats(-1).print_stats()
182
183The first method removed the extraneous path from all the module names. The
184second method sorted all the entries according to the standard module/line/name
185string that is printed. The third method printed out all the statistics.  You
186might try the following sort calls:
187
n188-.. % (this is to comply with the semantics of the old profiler).
n146+.. (this is to comply with the semantics of the old profiler).
189
190::
191
192   p.sort_stats('name')
193   p.print_stats()
194
195The first call will actually sort the list by function name, and the second call
196will print out the statistics.  The following are some interesting calls to
238   p.print_callees()
239   p.add('fooprof')
240
241Invoked as a script, the :mod:`pstats` module is a statistics browser for
242reading and examining profile dumps.  It has a simple line-oriented interface
243(implemented using :mod:`cmd`) and interactive help.
244
245
n204+.. _deterministic-profiling:
205+ 
246What Is Deterministic Profiling?
247================================
n248- 
249-.. _deterministic profiling:
250
251:dfn:`Deterministic profiling` is meant to reflect the fact that all *function
252call*, *function return*, and *exception* events are monitored, and precise
253timings are made for the intervals between these events (during which time the
254user's code is executing).  In contrast, :dfn:`statistical profiling` (which is
255not done by this module) randomly samples the effective instruction pointer, and
256deduces where time is being spent.  The latter technique traditionally involves
257less overhead (as the code does not need to be instrumented), but provides only
290standard entry points and functions.  For a more in-depth view of some of the
291code, consider reading the later section on Profiler Extensions, which includes
292discussion of how to derive "better" profilers from the classes presented, or
293reading the source code for these modules.
294
295
296.. function:: run(command[, filename])
297
n298-   This function takes a single argument that has can be passed to the
n256+   This function takes a single argument that can be passed to the
299-   :keyword:`exec` statement, and an optional file name.  In all cases this routine
257+   :keyword:`exec` statement, and an optional file name.  In all cases this
300-   attempts to :keyword:`exec` its first argument, and gather profiling statistics
258+   routine attempts to :keyword:`exec` its first argument, and gather profiling
301-   from the execution. If no file name is present, then this function automatically
259+   statistics from the execution. If no file name is present, then this function
302-   prints a simple profiling report, sorted by the standard name string (file/line
260+   automatically prints a simple profiling report, sorted by the standard name
303-   /function-name) that is presented in each line.  The following is a typical
261+   string (file/line/function-name) that is presented in each line.  The
304-   output from such a call::
262+   following is a typical output from such a call::
305
306            2706 function calls (2004 primitive calls) in 4.504 CPU seconds
307
308      Ordered by: standard name
309
310      ncalls  tottime  percall  cumtime  percall filename:lineno(function)
311           2    0.006    0.003    0.953    0.477 pobject.py:75(save_objects)
312        43/3    0.533    0.012    0.749    0.250 pobject.py:99(evaluate)
313       ...
314
315   The first line indicates that 2706 calls were monitored.  Of those calls, 2004
316   were :dfn:`primitive`.  We define :dfn:`primitive` to mean that the call was not
317   induced via recursion. The next line: ``Ordered by: standard name``, indicates
318   that the text string in the far right column was used to sort the output. The
319   column headings include:
320
n321-   ncalls 
n279+   ncalls
322      for the number of calls,
323
n324-   tottime 
n282+   tottime
325      for the total time spent in the given function (and excluding time made in calls
326      to sub-functions),
327
n328-   percall 
n286+   percall
329      is the quotient of ``tottime`` divided by ``ncalls``
330
n331-   cumtime 
n289+   cumtime
332      is the total time spent in this and all subfunctions (from invocation till
333      exit). This figure is accurate *even* for recursive functions.
334
n335-   percall 
n293+   percall
336      is the quotient of ``cumtime`` divided by primitive calls
337
n338-   filename:lineno(function) 
n296+   filename:lineno(function)
339      provides the respective data of each function
340
341   When there are two numbers in the first column (for example, ``43/3``), then the
342   latter is the number of primitive calls, and the former is the actual number of
343   calls.  Note that when the function does not recurse, these two values are the
344   same, and only the single figure is printed.
345
346
350   globals and locals dictionaries for the *command* string.
351
352Analysis of the profiler data is done using the :class:`Stats` class.
353
354.. note::
355
356   The :class:`Stats` class is defined in the :mod:`pstats` module.
357
n316+ 
358.. module:: pstats
n359- 
n318+   :synopsis: Statistics object for use with the profiler.
360- 
361-.. % now switch modules....
362-.. % (This \stmodindex use may be hard to change ;-( )
363
364
365.. class:: Stats(filename[, stream=sys.stdout[, ...]])
366
367   This class constructor creates an instance of a "statistics object" from a
368   *filename* (or set of filenames).  :class:`Stats` objects are manipulated by
369   methods, in order to print useful reports.  You may specify an alternate output
370   stream by giving the keyword argument, ``stream``.
373   corresponding version of :mod:`profile` or :mod:`cProfile`.  To be specific,
374   there is *no* file compatibility guaranteed with future versions of this
375   profiler, and there is no compatibility with files produced by other profilers.
376   If several files are provided, all the statistics for identical functions will
377   be coalesced, so that an overall view of several processes can be considered in
378   a single report.  If additional files need to be combined with data in an
379   existing :class:`Stats` object, the :meth:`add` method can be used.
380
n381-   .. % (such as the old system profiler).
n337+   .. (such as the old system profiler).
382
383   .. versionchanged:: 2.5
384      The *stream* parameter was added.
385
386
387.. _profile-stats:
388
389The :class:`Stats` Class
474   'file', 'line')``.
475
476   For backward-compatibility reasons, the numeric arguments ``-1``, ``0``, ``1``,
477   and ``2`` are permitted.  They are interpreted as ``'stdname'``, ``'calls'``,
478   ``'time'``, and ``'cumulative'`` respectively.  If this old style format
479   (numeric) is used, only one sort key (the numeric key) will be used, and
480   additional arguments will be silently ignored.
481
n482-   .. % For compatibility with the old profiler,
n438+   .. For compatibility with the old profiler,
483
484
485.. method:: Stats.reverse_order()
486
487   This method for the :class:`Stats` class reverses the ordering of the basic list
488   within the object.  Note that by default ascending vs descending order is
489   properly selected based on the sort key of choice.
490
n491-   .. % This method is provided primarily for
n447+   .. This method is provided primarily for compatibility with the old profiler.
492-   .. % compatibility with the old profiler.
493
494
495.. method:: Stats.print_stats([restriction, ...])
496
497   This method for the :class:`Stats` class prints out a report as described in the
498   :func:`profile.run` definition.
499
500   The order of the printing is based on the last :meth:`sort_stats` operation done
524.. method:: Stats.print_callers([restriction, ...])
525
526   This method for the :class:`Stats` class prints a list of all functions that
527   called each function in the profiled database.  The ordering is identical to
528   that provided by :meth:`print_stats`, and the definition of the restricting
529   argument is also identical.  Each caller is reported on its own line.  The
530   format differs slightly depending on the profiler that produced the stats:
531
n532-* With :mod:`profile`, a number is shown in parentheses after each caller to
n487+   * With :mod:`profile`, a number is shown in parentheses after each caller to
533-     show how many times this specific call was made.  For convenience, a second non-
488+     show how many times this specific call was made.  For convenience, a second
534-     parenthesized number repeats the cumulative time spent in the function at the
489+     non-parenthesized number repeats the cumulative time spent in the function
535-     right.
490+     at the right.
536
n537-* With :mod:`cProfile`, each caller is preceeded by three numbers: the number of
n492+   * With :mod:`cProfile`, each caller is preceded by three numbers: the number of
538     times this specific call was made, and the total and cumulative times spent in
539     the current function while it was invoked by this specific caller.
540
541
542.. method:: Stats.print_callees([restriction, ...])
543
544   This method for the :class:`Stats` class prints a list of all function that were
545   called by the indicated function.  Aside from this reversal of direction of
620
621   # 3. Specify computed bias in instance constructor.
622   pr = profile.Profile(bias=your_computed_bias)
623
624If you have a choice, you are better off choosing a smaller constant, and then
625your results will "less often" show up as negative in profile statistics.
626
627
n583+.. _profiler-extensions:
584+ 
628Extensions --- Deriving Better Profilers
629========================================
t630- 
631-.. _profiler extensions:
632
633The :class:`Profile` class of both modules, :mod:`profile` and :mod:`cProfile`,
634were written so that derived classes could be developed to extend the profiler.
635The details are not described here, as doing this successfully requires an
636expert understanding of how the :class:`Profile` class works internally.  Study
637the source code of the module carefully if you want to pursue this.
638
639If all you want to do is change how current time is determined (for example, to
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op