gooderp18绿色标准版
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1025 行
87KB

  1. <!DOCTYPE html>
  2. <html lang="en" data-content_root="../">
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
  6. <meta property="og:title" content="The Python Profilers" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/library/profile.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="Source code: Lib/profile.py and Lib/pstats.py Introduction to the profilers: cProfile and profile provide deterministic profiling of Python programs. A profile is a set of statistics that describes..." />
  11. <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
  12. <meta property="og:image:alt" content="Python documentation" />
  13. <meta name="description" content="Source code: Lib/profile.py and Lib/pstats.py Introduction to the profilers: cProfile and profile provide deterministic profiling of Python programs. A profile is a set of statistics that describes..." />
  14. <meta property="og:image:width" content="200" />
  15. <meta property="og:image:height" content="200" />
  16. <meta name="theme-color" content="#3776ab" />
  17. <title>The Python Profilers &#8212; Python 3.12.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
  18. <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=80d5e7a1" />
  19. <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=bb723527" />
  20. <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=b20cc3f5" />
  21. <script src="../_static/documentation_options.js?v=2c828074"></script>
  22. <script src="../_static/doctools.js?v=888ff710"></script>
  23. <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
  24. <script src="../_static/sidebar.js"></script>
  25. <link rel="search" type="application/opensearchdescription+xml"
  26. title="Search within Python 3.12.3 documentation"
  27. href="../_static/opensearch.xml"/>
  28. <link rel="author" title="About these documents" href="../about.html" />
  29. <link rel="index" title="Index" href="../genindex.html" />
  30. <link rel="search" title="Search" href="../search.html" />
  31. <link rel="copyright" title="Copyright" href="../copyright.html" />
  32. <link rel="next" title="timeit — Measure execution time of small code snippets" href="timeit.html" />
  33. <link rel="prev" title="pdb — The Python Debugger" href="pdb.html" />
  34. <link rel="canonical" href="https://docs.python.org/3/library/profile.html" />
  35. <style>
  36. @media only screen {
  37. table.full-width-table {
  38. width: 100%;
  39. }
  40. }
  41. </style>
  42. <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
  43. <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
  44. <script type="text/javascript" src="../_static/copybutton.js"></script>
  45. <script type="text/javascript" src="../_static/menu.js"></script>
  46. <script type="text/javascript" src="../_static/search-focus.js"></script>
  47. <script type="text/javascript" src="../_static/themetoggle.js"></script>
  48. </head>
  49. <body>
  50. <div class="mobile-nav">
  51. <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
  52. aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
  53. <nav class="nav-content" role="navigation">
  54. <label for="menuToggler" class="toggler__label">
  55. <span></span>
  56. </label>
  57. <span class="nav-items-wrapper">
  58. <a href="https://www.python.org/" class="nav-logo">
  59. <img src="../_static/py.svg" alt="Python logo"/>
  60. </a>
  61. <span class="version_switcher_placeholder"></span>
  62. <form role="search" class="search" action="../search.html" method="get">
  63. <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
  64. <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
  65. </svg>
  66. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  67. <input type="submit" value="Go"/>
  68. </form>
  69. </span>
  70. </nav>
  71. <div class="menu-wrapper">
  72. <nav class="menu" role="navigation" aria-label="main navigation">
  73. <div class="language_switcher_placeholder"></div>
  74. <label class="theme-selector-label">
  75. Theme
  76. <select class="theme-selector" oninput="activateTheme(this.value)">
  77. <option value="auto" selected>Auto</option>
  78. <option value="light">Light</option>
  79. <option value="dark">Dark</option>
  80. </select>
  81. </label>
  82. <div>
  83. <h3><a href="../contents.html">Table of Contents</a></h3>
  84. <ul>
  85. <li><a class="reference internal" href="#">The Python Profilers</a><ul>
  86. <li><a class="reference internal" href="#introduction-to-the-profilers">Introduction to the profilers</a></li>
  87. <li><a class="reference internal" href="#instant-user-s-manual">Instant User’s Manual</a></li>
  88. <li><a class="reference internal" href="#module-cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code> Module Reference</a></li>
  89. <li><a class="reference internal" href="#the-stats-class">The <code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code> Class</a></li>
  90. <li><a class="reference internal" href="#what-is-deterministic-profiling">What Is Deterministic Profiling?</a></li>
  91. <li><a class="reference internal" href="#limitations">Limitations</a></li>
  92. <li><a class="reference internal" href="#calibration">Calibration</a></li>
  93. <li><a class="reference internal" href="#using-a-custom-timer">Using a custom timer</a></li>
  94. </ul>
  95. </li>
  96. </ul>
  97. </div>
  98. <div>
  99. <h4>Previous topic</h4>
  100. <p class="topless"><a href="pdb.html"
  101. title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pdb</span></code> — The Python Debugger</a></p>
  102. </div>
  103. <div>
  104. <h4>Next topic</h4>
  105. <p class="topless"><a href="timeit.html"
  106. title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">timeit</span></code> — Measure execution time of small code snippets</a></p>
  107. </div>
  108. <div role="note" aria-label="source link">
  109. <h3>This Page</h3>
  110. <ul class="this-page-menu">
  111. <li><a href="../bugs.html">Report a Bug</a></li>
  112. <li>
  113. <a href="https://github.com/python/cpython/blob/main/Doc/library/profile.rst"
  114. rel="nofollow">Show Source
  115. </a>
  116. </li>
  117. </ul>
  118. </div>
  119. </nav>
  120. </div>
  121. </div>
  122. <div class="related" role="navigation" aria-label="related navigation">
  123. <h3>Navigation</h3>
  124. <ul>
  125. <li class="right" style="margin-right: 10px">
  126. <a href="../genindex.html" title="General Index"
  127. accesskey="I">index</a></li>
  128. <li class="right" >
  129. <a href="../py-modindex.html" title="Python Module Index"
  130. >modules</a> |</li>
  131. <li class="right" >
  132. <a href="timeit.html" title="timeit — Measure execution time of small code snippets"
  133. accesskey="N">next</a> |</li>
  134. <li class="right" >
  135. <a href="pdb.html" title="pdb — The Python Debugger"
  136. accesskey="P">previous</a> |</li>
  137. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  138. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  139. <li class="switchers">
  140. <div class="language_switcher_placeholder"></div>
  141. <div class="version_switcher_placeholder"></div>
  142. </li>
  143. <li>
  144. </li>
  145. <li id="cpython-language-and-version">
  146. <a href="../index.html">3.12.3 Documentation</a> &#187;
  147. </li>
  148. <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
  149. <li class="nav-item nav-item-2"><a href="debug.html" accesskey="U">Debugging and Profiling</a> &#187;</li>
  150. <li class="nav-item nav-item-this"><a href="">The Python Profilers</a></li>
  151. <li class="right">
  152. <div class="inline-search" role="search">
  153. <form class="inline-search" action="../search.html" method="get">
  154. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  155. <input type="submit" value="Go" />
  156. </form>
  157. </div>
  158. |
  159. </li>
  160. <li class="right">
  161. <label class="theme-selector-label">
  162. Theme
  163. <select class="theme-selector" oninput="activateTheme(this.value)">
  164. <option value="auto" selected>Auto</option>
  165. <option value="light">Light</option>
  166. <option value="dark">Dark</option>
  167. </select>
  168. </label> |</li>
  169. </ul>
  170. </div>
  171. <div class="document">
  172. <div class="documentwrapper">
  173. <div class="bodywrapper">
  174. <div class="body" role="main">
  175. <section id="the-python-profilers">
  176. <span id="profile"></span><h1>The Python Profilers<a class="headerlink" href="#the-python-profilers" title="Link to this heading">¶</a></h1>
  177. <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/profile.py">Lib/profile.py</a> and <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/pstats.py">Lib/pstats.py</a></p>
  178. <hr class="docutils" />
  179. <section id="introduction-to-the-profilers">
  180. <span id="profiler-introduction"></span><h2>Introduction to the profilers<a class="headerlink" href="#introduction-to-the-profilers" title="Link to this heading">¶</a></h2>
  181. <p id="index-0"><a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a> and <a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> provide <em class="dfn">deterministic profiling</em> of
  182. Python programs. A <em class="dfn">profile</em> is a set of statistics that describes how
  183. often and for how long various parts of the program executed. These statistics
  184. can be formatted into reports via the <a class="reference internal" href="#module-pstats" title="pstats: Statistics object for use with the profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pstats</span></code></a> module.</p>
  185. <p>The Python standard library provides two different implementations of the same
  186. profiling interface:</p>
  187. <ol class="arabic simple">
  188. <li><p><a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a> is recommended for most users; it’s a C extension with
  189. reasonable overhead that makes it suitable for profiling long-running
  190. programs. Based on <code class="xref py py-mod docutils literal notranslate"><span class="pre">lsprof</span></code>, contributed by Brett Rosen and Ted
  191. Czotter.</p></li>
  192. <li><p><a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a>, a pure Python module whose interface is imitated by
  193. <a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a>, but which adds significant overhead to profiled programs.
  194. If you’re trying to extend the profiler in some way, the task might be easier
  195. with this module. Originally designed and written by Jim Roskind.</p></li>
  196. </ol>
  197. <div class="admonition note">
  198. <p class="admonition-title">Note</p>
  199. <p>The profiler modules are designed to provide an execution profile for a given
  200. program, not for benchmarking purposes (for that, there is <a class="reference internal" href="timeit.html#module-timeit" title="timeit: Measure the execution time of small code snippets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">timeit</span></code></a> for
  201. reasonably accurate results). This particularly applies to benchmarking
  202. Python code against C code: the profilers introduce overhead for Python code,
  203. but not for C-level functions, and so the C code would seem faster than any
  204. Python one.</p>
  205. </div>
  206. </section>
  207. <section id="instant-user-s-manual">
  208. <span id="profile-instant"></span><h2>Instant User’s Manual<a class="headerlink" href="#instant-user-s-manual" title="Link to this heading">¶</a></h2>
  209. <p>This section is provided for users that “don’t want to read the manual.” It
  210. provides a very brief overview, and allows a user to rapidly perform profiling
  211. on an existing application.</p>
  212. <p>To profile a function that takes a single argument, you can do:</p>
  213. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cProfile</span>
  214. <span class="kn">import</span> <span class="nn">re</span>
  215. <span class="n">cProfile</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="s1">&#39;re.compile(&quot;foo|bar&quot;)&#39;</span><span class="p">)</span>
  216. </pre></div>
  217. </div>
  218. <p>(Use <a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> instead of <a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a> if the latter is not available on
  219. your system.)</p>
  220. <p>The above action would run <a class="reference internal" href="re.html#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a> and print profile results like
  221. the following:</p>
  222. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span> <span class="mi">214</span> <span class="n">function</span> <span class="n">calls</span> <span class="p">(</span><span class="mi">207</span> <span class="n">primitive</span> <span class="n">calls</span><span class="p">)</span> <span class="ow">in</span> <span class="mf">0.002</span> <span class="n">seconds</span>
  223. <span class="n">Ordered</span> <span class="n">by</span><span class="p">:</span> <span class="n">cumulative</span> <span class="n">time</span>
  224. <span class="n">ncalls</span> <span class="n">tottime</span> <span class="n">percall</span> <span class="n">cumtime</span> <span class="n">percall</span> <span class="n">filename</span><span class="p">:</span><span class="n">lineno</span><span class="p">(</span><span class="n">function</span><span class="p">)</span>
  225. <span class="mi">1</span> <span class="mf">0.000</span> <span class="mf">0.000</span> <span class="mf">0.002</span> <span class="mf">0.002</span> <span class="p">{</span><span class="n">built</span><span class="o">-</span><span class="ow">in</span> <span class="n">method</span> <span class="n">builtins</span><span class="o">.</span><span class="n">exec</span><span class="p">}</span>
  226. <span class="mi">1</span> <span class="mf">0.000</span> <span class="mf">0.000</span> <span class="mf">0.001</span> <span class="mf">0.001</span> <span class="o">&lt;</span><span class="n">string</span><span class="o">&gt;</span><span class="p">:</span><span class="mi">1</span><span class="p">(</span><span class="o">&lt;</span><span class="n">module</span><span class="o">&gt;</span><span class="p">)</span>
  227. <span class="mi">1</span> <span class="mf">0.000</span> <span class="mf">0.000</span> <span class="mf">0.001</span> <span class="mf">0.001</span> <span class="fm">__init__</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">250</span><span class="p">(</span><span class="nb">compile</span><span class="p">)</span>
  228. <span class="mi">1</span> <span class="mf">0.000</span> <span class="mf">0.000</span> <span class="mf">0.001</span> <span class="mf">0.001</span> <span class="fm">__init__</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">289</span><span class="p">(</span><span class="n">_compile</span><span class="p">)</span>
  229. <span class="mi">1</span> <span class="mf">0.000</span> <span class="mf">0.000</span> <span class="mf">0.000</span> <span class="mf">0.000</span> <span class="n">_compiler</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">759</span><span class="p">(</span><span class="nb">compile</span><span class="p">)</span>
  230. <span class="mi">1</span> <span class="mf">0.000</span> <span class="mf">0.000</span> <span class="mf">0.000</span> <span class="mf">0.000</span> <span class="n">_parser</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">937</span><span class="p">(</span><span class="n">parse</span><span class="p">)</span>
  231. <span class="mi">1</span> <span class="mf">0.000</span> <span class="mf">0.000</span> <span class="mf">0.000</span> <span class="mf">0.000</span> <span class="n">_compiler</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">598</span><span class="p">(</span><span class="n">_code</span><span class="p">)</span>
  232. <span class="mi">1</span> <span class="mf">0.000</span> <span class="mf">0.000</span> <span class="mf">0.000</span> <span class="mf">0.000</span> <span class="n">_parser</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">435</span><span class="p">(</span><span class="n">_parse_sub</span><span class="p">)</span>
  233. </pre></div>
  234. </div>
  235. <p>The first line indicates that 214 calls were monitored. Of those calls, 207
  236. were <em class="dfn">primitive</em>, meaning that the call was not induced via recursion. The
  237. next line: <code class="docutils literal notranslate"><span class="pre">Ordered</span> <span class="pre">by:</span> <span class="pre">cumulative</span> <span class="pre">time</span></code> indicates the output is sorted
  238. by the <code class="docutils literal notranslate"><span class="pre">cumtime</span></code> values. The column headings include:</p>
  239. <dl class="simple">
  240. <dt>ncalls</dt><dd><p>for the number of calls.</p>
  241. </dd>
  242. <dt>tottime</dt><dd><p>for the total time spent in the given function (and excluding time made in
  243. calls to sub-functions)</p>
  244. </dd>
  245. <dt>percall</dt><dd><p>is the quotient of <code class="docutils literal notranslate"><span class="pre">tottime</span></code> divided by <code class="docutils literal notranslate"><span class="pre">ncalls</span></code></p>
  246. </dd>
  247. <dt>cumtime</dt><dd><p>is the cumulative time spent in this and all subfunctions (from invocation
  248. till exit). This figure is accurate <em>even</em> for recursive functions.</p>
  249. </dd>
  250. <dt>percall</dt><dd><p>is the quotient of <code class="docutils literal notranslate"><span class="pre">cumtime</span></code> divided by primitive calls</p>
  251. </dd>
  252. <dt>filename:lineno(function)</dt><dd><p>provides the respective data of each function</p>
  253. </dd>
  254. </dl>
  255. <p>When there are two numbers in the first column (for example <code class="docutils literal notranslate"><span class="pre">3/1</span></code>), it means
  256. that the function recursed. The second value is the number of primitive calls
  257. and the former is the total number of calls. Note that when the function does
  258. not recurse, these two values are the same, and only the single figure is
  259. printed.</p>
  260. <p>Instead of printing the output at the end of the profile run, you can save the
  261. results to a file by specifying a filename to the <code class="xref py py-func docutils literal notranslate"><span class="pre">run()</span></code> function:</p>
  262. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cProfile</span>
  263. <span class="kn">import</span> <span class="nn">re</span>
  264. <span class="n">cProfile</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="s1">&#39;re.compile(&quot;foo|bar&quot;)&#39;</span><span class="p">,</span> <span class="s1">&#39;restats&#39;</span><span class="p">)</span>
  265. </pre></div>
  266. </div>
  267. <p>The <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">pstats.Stats</span></code></a> class reads profile results from a file and formats
  268. them in various ways.</p>
  269. <p id="profile-cli">The files <a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a> and <a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> can also be invoked as a script to
  270. profile another script. For example:</p>
  271. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">cProfile</span> <span class="p">[</span><span class="o">-</span><span class="n">o</span> <span class="n">output_file</span><span class="p">]</span> <span class="p">[</span><span class="o">-</span><span class="n">s</span> <span class="n">sort_order</span><span class="p">]</span> <span class="p">(</span><span class="o">-</span><span class="n">m</span> <span class="n">module</span> <span class="o">|</span> <span class="n">myscript</span><span class="o">.</span><span class="n">py</span><span class="p">)</span>
  272. </pre></div>
  273. </div>
  274. <p><code class="docutils literal notranslate"><span class="pre">-o</span></code> writes the profile results to a file instead of to stdout</p>
  275. <p><code class="docutils literal notranslate"><span class="pre">-s</span></code> specifies one of the <a class="reference internal" href="#pstats.Stats.sort_stats" title="pstats.Stats.sort_stats"><code class="xref py py-func docutils literal notranslate"><span class="pre">sort_stats()</span></code></a> sort values to sort
  276. the output by. This only applies when <code class="docutils literal notranslate"><span class="pre">-o</span></code> is not supplied.</p>
  277. <p><code class="docutils literal notranslate"><span class="pre">-m</span></code> specifies that a module is being profiled instead of a script.</p>
  278. <div class="versionadded">
  279. <p><span class="versionmodified added">New in version 3.7: </span>Added the <code class="docutils literal notranslate"><span class="pre">-m</span></code> option to <a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a>.</p>
  280. </div>
  281. <div class="versionadded">
  282. <p><span class="versionmodified added">New in version 3.8: </span>Added the <code class="docutils literal notranslate"><span class="pre">-m</span></code> option to <a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a>.</p>
  283. </div>
  284. <p>The <a class="reference internal" href="#module-pstats" title="pstats: Statistics object for use with the profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pstats</span></code></a> module’s <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> class has a variety of methods
  285. for manipulating and printing the data saved into a profile results file:</p>
  286. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">pstats</span>
  287. <span class="kn">from</span> <span class="nn">pstats</span> <span class="kn">import</span> <span class="n">SortKey</span>
  288. <span class="n">p</span> <span class="o">=</span> <span class="n">pstats</span><span class="o">.</span><span class="n">Stats</span><span class="p">(</span><span class="s1">&#39;restats&#39;</span><span class="p">)</span>
  289. <span class="n">p</span><span class="o">.</span><span class="n">strip_dirs</span><span class="p">()</span><span class="o">.</span><span class="n">sort_stats</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">print_stats</span><span class="p">()</span>
  290. </pre></div>
  291. </div>
  292. <p>The <a class="reference internal" href="#pstats.Stats.strip_dirs" title="pstats.Stats.strip_dirs"><code class="xref py py-meth docutils literal notranslate"><span class="pre">strip_dirs()</span></code></a> method removed the extraneous path from all
  293. the module names. The <a class="reference internal" href="#pstats.Stats.sort_stats" title="pstats.Stats.sort_stats"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sort_stats()</span></code></a> method sorted all the
  294. entries according to the standard module/line/name string that is printed. The
  295. <a class="reference internal" href="#pstats.Stats.print_stats" title="pstats.Stats.print_stats"><code class="xref py py-meth docutils literal notranslate"><span class="pre">print_stats()</span></code></a> method printed out all the statistics. You
  296. might try the following sort calls:</p>
  297. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">p</span><span class="o">.</span><span class="n">sort_stats</span><span class="p">(</span><span class="n">SortKey</span><span class="o">.</span><span class="n">NAME</span><span class="p">)</span>
  298. <span class="n">p</span><span class="o">.</span><span class="n">print_stats</span><span class="p">()</span>
  299. </pre></div>
  300. </div>
  301. <p>The first call will actually sort the list by function name, and the second call
  302. will print out the statistics. The following are some interesting calls to
  303. experiment with:</p>
  304. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">p</span><span class="o">.</span><span class="n">sort_stats</span><span class="p">(</span><span class="n">SortKey</span><span class="o">.</span><span class="n">CUMULATIVE</span><span class="p">)</span><span class="o">.</span><span class="n">print_stats</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
  305. </pre></div>
  306. </div>
  307. <p>This sorts the profile by cumulative time in a function, and then only prints
  308. the ten most significant lines. If you want to understand what algorithms are
  309. taking time, the above line is what you would use.</p>
  310. <p>If you were looking to see what functions were looping a lot, and taking a lot
  311. of time, you would do:</p>
  312. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">p</span><span class="o">.</span><span class="n">sort_stats</span><span class="p">(</span><span class="n">SortKey</span><span class="o">.</span><span class="n">TIME</span><span class="p">)</span><span class="o">.</span><span class="n">print_stats</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
  313. </pre></div>
  314. </div>
  315. <p>to sort according to time spent within each function, and then print the
  316. statistics for the top ten functions.</p>
  317. <p>You might also try:</p>
  318. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">p</span><span class="o">.</span><span class="n">sort_stats</span><span class="p">(</span><span class="n">SortKey</span><span class="o">.</span><span class="n">FILENAME</span><span class="p">)</span><span class="o">.</span><span class="n">print_stats</span><span class="p">(</span><span class="s1">&#39;__init__&#39;</span><span class="p">)</span>
  319. </pre></div>
  320. </div>
  321. <p>This will sort all the statistics by file name, and then print out statistics
  322. for only the class init methods (since they are spelled with <code class="docutils literal notranslate"><span class="pre">__init__</span></code> in
  323. them). As one final example, you could try:</p>
  324. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">p</span><span class="o">.</span><span class="n">sort_stats</span><span class="p">(</span><span class="n">SortKey</span><span class="o">.</span><span class="n">TIME</span><span class="p">,</span> <span class="n">SortKey</span><span class="o">.</span><span class="n">CUMULATIVE</span><span class="p">)</span><span class="o">.</span><span class="n">print_stats</span><span class="p">(</span><span class="mf">.5</span><span class="p">,</span> <span class="s1">&#39;init&#39;</span><span class="p">)</span>
  325. </pre></div>
  326. </div>
  327. <p>This line sorts statistics with a primary key of time, and a secondary key of
  328. cumulative time, and then prints out some of the statistics. To be specific, the
  329. list is first culled down to 50% (re: <code class="docutils literal notranslate"><span class="pre">.5</span></code>) of its original size, then only
  330. lines containing <code class="docutils literal notranslate"><span class="pre">init</span></code> are maintained, and that sub-sub-list is printed.</p>
  331. <p>If you wondered what functions called the above functions, you could now (<code class="docutils literal notranslate"><span class="pre">p</span></code>
  332. is still sorted according to the last criteria) do:</p>
  333. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">p</span><span class="o">.</span><span class="n">print_callers</span><span class="p">(</span><span class="mf">.5</span><span class="p">,</span> <span class="s1">&#39;init&#39;</span><span class="p">)</span>
  334. </pre></div>
  335. </div>
  336. <p>and you would get a list of callers for each of the listed functions.</p>
  337. <p>If you want more functionality, you’re going to have to read the manual, or
  338. guess what the following functions do:</p>
  339. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">p</span><span class="o">.</span><span class="n">print_callees</span><span class="p">()</span>
  340. <span class="n">p</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="s1">&#39;restats&#39;</span><span class="p">)</span>
  341. </pre></div>
  342. </div>
  343. <p>Invoked as a script, the <a class="reference internal" href="#module-pstats" title="pstats: Statistics object for use with the profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pstats</span></code></a> module is a statistics browser for
  344. reading and examining profile dumps. It has a simple line-oriented interface
  345. (implemented using <a class="reference internal" href="cmd.html#module-cmd" title="cmd: Build line-oriented command interpreters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmd</span></code></a>) and interactive help.</p>
  346. </section>
  347. <section id="module-cProfile">
  348. <span id="profile-and-cprofile-module-reference"></span><h2><a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> and <a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a> Module Reference<a class="headerlink" href="#module-cProfile" title="Link to this heading">¶</a></h2>
  349. <p id="module-profile">Both the <a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> and <a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a> modules provide the following
  350. functions:</p>
  351. <dl class="py function">
  352. <dt class="sig sig-object py" id="profile.run">
  353. <span class="sig-prename descclassname"><span class="pre">profile.</span></span><span class="sig-name descname"><span class="pre">run</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">command</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">filename</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">sort</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">-1</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#profile.run" title="Link to this definition">¶</a></dt>
  354. <dd><p>This function takes a single argument that can be passed to the <a class="reference internal" href="functions.html#exec" title="exec"><code class="xref py py-func docutils literal notranslate"><span class="pre">exec()</span></code></a>
  355. function, and an optional file name. In all cases this routine executes:</p>
  356. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">exec</span><span class="p">(</span><span class="n">command</span><span class="p">,</span> <span class="n">__main__</span><span class="o">.</span><span class="vm">__dict__</span><span class="p">,</span> <span class="n">__main__</span><span class="o">.</span><span class="vm">__dict__</span><span class="p">)</span>
  357. </pre></div>
  358. </div>
  359. <p>and gathers profiling statistics from the execution. If no file name is
  360. present, then this function automatically creates a <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a>
  361. instance and prints a simple profiling report. If the sort value is specified,
  362. it is passed to this <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> instance to control how the
  363. results are sorted.</p>
  364. </dd></dl>
  365. <dl class="py function">
  366. <dt class="sig sig-object py" id="profile.runctx">
  367. <span class="sig-prename descclassname"><span class="pre">profile.</span></span><span class="sig-name descname"><span class="pre">runctx</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">command</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">globals</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">locals</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">filename</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">sort</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">-1</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#profile.runctx" title="Link to this definition">¶</a></dt>
  368. <dd><p>This function is similar to <a class="reference internal" href="#profile.run" title="profile.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">run()</span></code></a>, with added arguments to supply the
  369. globals and locals dictionaries for the <em>command</em> string. This routine
  370. executes:</p>
  371. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">exec</span><span class="p">(</span><span class="n">command</span><span class="p">,</span> <span class="nb">globals</span><span class="p">,</span> <span class="nb">locals</span><span class="p">)</span>
  372. </pre></div>
  373. </div>
  374. <p>and gathers profiling statistics as in the <a class="reference internal" href="#profile.run" title="profile.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">run()</span></code></a> function above.</p>
  375. </dd></dl>
  376. <dl class="py class">
  377. <dt class="sig sig-object py" id="profile.Profile">
  378. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">profile.</span></span><span class="sig-name descname"><span class="pre">Profile</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">timer</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">timeunit</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0.0</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">subcalls</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">builtins</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#profile.Profile" title="Link to this definition">¶</a></dt>
  379. <dd><p>This class is normally only used if more precise control over profiling is
  380. needed than what the <code class="xref py py-func docutils literal notranslate"><span class="pre">cProfile.run()</span></code> function provides.</p>
  381. <p>A custom timer can be supplied for measuring how long code takes to run via
  382. the <em>timer</em> argument. This must be a function that returns a single number
  383. representing the current time. If the number is an integer, the <em>timeunit</em>
  384. specifies a multiplier that specifies the duration of each unit of time. For
  385. example, if the timer returns times measured in thousands of seconds, the
  386. time unit would be <code class="docutils literal notranslate"><span class="pre">.001</span></code>.</p>
  387. <p>Directly using the <a class="reference internal" href="#profile.Profile" title="profile.Profile"><code class="xref py py-class docutils literal notranslate"><span class="pre">Profile</span></code></a> class allows formatting profile results
  388. without writing the profile data to a file:</p>
  389. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cProfile</span><span class="o">,</span> <span class="nn">pstats</span><span class="o">,</span> <span class="nn">io</span>
  390. <span class="kn">from</span> <span class="nn">pstats</span> <span class="kn">import</span> <span class="n">SortKey</span>
  391. <span class="n">pr</span> <span class="o">=</span> <span class="n">cProfile</span><span class="o">.</span><span class="n">Profile</span><span class="p">()</span>
  392. <span class="n">pr</span><span class="o">.</span><span class="n">enable</span><span class="p">()</span>
  393. <span class="c1"># ... do something ...</span>
  394. <span class="n">pr</span><span class="o">.</span><span class="n">disable</span><span class="p">()</span>
  395. <span class="n">s</span> <span class="o">=</span> <span class="n">io</span><span class="o">.</span><span class="n">StringIO</span><span class="p">()</span>
  396. <span class="n">sortby</span> <span class="o">=</span> <span class="n">SortKey</span><span class="o">.</span><span class="n">CUMULATIVE</span>
  397. <span class="n">ps</span> <span class="o">=</span> <span class="n">pstats</span><span class="o">.</span><span class="n">Stats</span><span class="p">(</span><span class="n">pr</span><span class="p">,</span> <span class="n">stream</span><span class="o">=</span><span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">sort_stats</span><span class="p">(</span><span class="n">sortby</span><span class="p">)</span>
  398. <span class="n">ps</span><span class="o">.</span><span class="n">print_stats</span><span class="p">()</span>
  399. <span class="nb">print</span><span class="p">(</span><span class="n">s</span><span class="o">.</span><span class="n">getvalue</span><span class="p">())</span>
  400. </pre></div>
  401. </div>
  402. <p>The <a class="reference internal" href="#profile.Profile" title="profile.Profile"><code class="xref py py-class docutils literal notranslate"><span class="pre">Profile</span></code></a> class can also be used as a context manager (supported
  403. only in <a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a> module. see <a class="reference internal" href="stdtypes.html#typecontextmanager"><span class="std std-ref">Context Manager Types</span></a>):</p>
  404. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cProfile</span>
  405. <span class="k">with</span> <span class="n">cProfile</span><span class="o">.</span><span class="n">Profile</span><span class="p">()</span> <span class="k">as</span> <span class="n">pr</span><span class="p">:</span>
  406. <span class="c1"># ... do something ...</span>
  407. <span class="n">pr</span><span class="o">.</span><span class="n">print_stats</span><span class="p">()</span>
  408. </pre></div>
  409. </div>
  410. <div class="versionchanged">
  411. <p><span class="versionmodified changed">Changed in version 3.8: </span>Added context manager support.</p>
  412. </div>
  413. <dl class="py method">
  414. <dt class="sig sig-object py" id="profile.Profile.enable">
  415. <span class="sig-name descname"><span class="pre">enable</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#profile.Profile.enable" title="Link to this definition">¶</a></dt>
  416. <dd><p>Start collecting profiling data. Only in <a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a>.</p>
  417. </dd></dl>
  418. <dl class="py method">
  419. <dt class="sig sig-object py" id="profile.Profile.disable">
  420. <span class="sig-name descname"><span class="pre">disable</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#profile.Profile.disable" title="Link to this definition">¶</a></dt>
  421. <dd><p>Stop collecting profiling data. Only in <a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a>.</p>
  422. </dd></dl>
  423. <dl class="py method">
  424. <dt class="sig sig-object py" id="profile.Profile.create_stats">
  425. <span class="sig-name descname"><span class="pre">create_stats</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#profile.Profile.create_stats" title="Link to this definition">¶</a></dt>
  426. <dd><p>Stop collecting profiling data and record the results internally
  427. as the current profile.</p>
  428. </dd></dl>
  429. <dl class="py method">
  430. <dt class="sig sig-object py" id="profile.Profile.print_stats">
  431. <span class="sig-name descname"><span class="pre">print_stats</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">sort</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">-1</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#profile.Profile.print_stats" title="Link to this definition">¶</a></dt>
  432. <dd><p>Create a <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> object based on the current
  433. profile and print the results to stdout.</p>
  434. </dd></dl>
  435. <dl class="py method">
  436. <dt class="sig sig-object py" id="profile.Profile.dump_stats">
  437. <span class="sig-name descname"><span class="pre">dump_stats</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">filename</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#profile.Profile.dump_stats" title="Link to this definition">¶</a></dt>
  438. <dd><p>Write the results of the current profile to <em>filename</em>.</p>
  439. </dd></dl>
  440. <dl class="py method">
  441. <dt class="sig sig-object py" id="profile.Profile.run">
  442. <span class="sig-name descname"><span class="pre">run</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">cmd</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#profile.Profile.run" title="Link to this definition">¶</a></dt>
  443. <dd><p>Profile the cmd via <a class="reference internal" href="functions.html#exec" title="exec"><code class="xref py py-func docutils literal notranslate"><span class="pre">exec()</span></code></a>.</p>
  444. </dd></dl>
  445. <dl class="py method">
  446. <dt class="sig sig-object py" id="profile.Profile.runctx">
  447. <span class="sig-name descname"><span class="pre">runctx</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">cmd</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">globals</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">locals</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#profile.Profile.runctx" title="Link to this definition">¶</a></dt>
  448. <dd><p>Profile the cmd via <a class="reference internal" href="functions.html#exec" title="exec"><code class="xref py py-func docutils literal notranslate"><span class="pre">exec()</span></code></a> with the specified global and
  449. local environment.</p>
  450. </dd></dl>
  451. <dl class="py method">
  452. <dt class="sig sig-object py" id="profile.Profile.runcall">
  453. <span class="sig-name descname"><span class="pre">runcall</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">func</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">/</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwargs</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#profile.Profile.runcall" title="Link to this definition">¶</a></dt>
  454. <dd><p>Profile <code class="docutils literal notranslate"><span class="pre">func(*args,</span> <span class="pre">**kwargs)</span></code></p>
  455. </dd></dl>
  456. </dd></dl>
  457. <p>Note that profiling will only work if the called command/function actually
  458. returns. If the interpreter is terminated (e.g. via a <a class="reference internal" href="sys.html#sys.exit" title="sys.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code></a> call
  459. during the called command/function execution) no profiling results will be
  460. printed.</p>
  461. </section>
  462. <section id="the-stats-class">
  463. <span id="profile-stats"></span><h2>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code> Class<a class="headerlink" href="#the-stats-class" title="Link to this heading">¶</a></h2>
  464. <p>Analysis of the profiler data is done using the <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> class.</p>
  465. <dl class="py class" id="module-pstats">
  466. <dt class="sig sig-object py" id="pstats.Stats">
  467. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">pstats.</span></span><span class="sig-name descname"><span class="pre">Stats</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">*filenames</span> <span class="pre">or</span> <span class="pre">profile</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">stream=sys.stdout</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pstats.Stats" title="Link to this definition">¶</a></dt>
  468. <dd><p>This class constructor creates an instance of a “statistics object” from a
  469. <em>filename</em> (or list of filenames) or from a <code class="xref py py-class docutils literal notranslate"><span class="pre">Profile</span></code> instance. Output
  470. will be printed to the stream specified by <em>stream</em>.</p>
  471. <p>The file selected by the above constructor must have been created by the
  472. corresponding version of <a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> or <a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a>. To be specific,
  473. there is <em>no</em> file compatibility guaranteed with future versions of this
  474. profiler, and there is no compatibility with files produced by other
  475. profilers, or the same profiler run on a different operating system. If
  476. several files are provided, all the statistics for identical functions will
  477. be coalesced, so that an overall view of several processes can be considered
  478. in a single report. If additional files need to be combined with data in an
  479. existing <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> object, the <a class="reference internal" href="#pstats.Stats.add" title="pstats.Stats.add"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code></a> method
  480. can be used.</p>
  481. <p>Instead of reading the profile data from a file, a <code class="xref py py-class docutils literal notranslate"><span class="pre">cProfile.Profile</span></code>
  482. or <a class="reference internal" href="#profile.Profile" title="profile.Profile"><code class="xref py py-class docutils literal notranslate"><span class="pre">profile.Profile</span></code></a> object can be used as the profile data source.</p>
  483. <p><a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> objects have the following methods:</p>
  484. <dl class="py method">
  485. <dt class="sig sig-object py" id="pstats.Stats.strip_dirs">
  486. <span class="sig-name descname"><span class="pre">strip_dirs</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pstats.Stats.strip_dirs" title="Link to this definition">¶</a></dt>
  487. <dd><p>This method for the <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> class removes all leading path
  488. information from file names. It is very useful in reducing the size of
  489. the printout to fit within (close to) 80 columns. This method modifies
  490. the object, and the stripped information is lost. After performing a
  491. strip operation, the object is considered to have its entries in a
  492. “random” order, as it was just after object initialization and loading.
  493. If <a class="reference internal" href="#pstats.Stats.strip_dirs" title="pstats.Stats.strip_dirs"><code class="xref py py-meth docutils literal notranslate"><span class="pre">strip_dirs()</span></code></a> causes two function names to be
  494. indistinguishable (they are on the same line of the same filename, and
  495. have the same function name), then the statistics for these two entries
  496. are accumulated into a single entry.</p>
  497. </dd></dl>
  498. <dl class="py method">
  499. <dt class="sig sig-object py" id="pstats.Stats.add">
  500. <span class="sig-name descname"><span class="pre">add</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">filenames</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pstats.Stats.add" title="Link to this definition">¶</a></dt>
  501. <dd><p>This method of the <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> class accumulates additional profiling
  502. information into the current profiling object. Its arguments should refer
  503. to filenames created by the corresponding version of <a class="reference internal" href="#profile.run" title="profile.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">profile.run()</span></code></a>
  504. or <code class="xref py py-func docutils literal notranslate"><span class="pre">cProfile.run()</span></code>. Statistics for identically named (re: file, line,
  505. name) functions are automatically accumulated into single function
  506. statistics.</p>
  507. </dd></dl>
  508. <dl class="py method">
  509. <dt class="sig sig-object py" id="pstats.Stats.dump_stats">
  510. <span class="sig-name descname"><span class="pre">dump_stats</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">filename</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pstats.Stats.dump_stats" title="Link to this definition">¶</a></dt>
  511. <dd><p>Save the data loaded into the <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> object to a file named
  512. <em>filename</em>. The file is created if it does not exist, and is overwritten
  513. if it already exists. This is equivalent to the method of the same name
  514. on the <a class="reference internal" href="#profile.Profile" title="profile.Profile"><code class="xref py py-class docutils literal notranslate"><span class="pre">profile.Profile</span></code></a> and <code class="xref py py-class docutils literal notranslate"><span class="pre">cProfile.Profile</span></code> classes.</p>
  515. </dd></dl>
  516. <dl class="py method">
  517. <dt class="sig sig-object py" id="pstats.Stats.sort_stats">
  518. <span class="sig-name descname"><span class="pre">sort_stats</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">keys</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pstats.Stats.sort_stats" title="Link to this definition">¶</a></dt>
  519. <dd><p>This method modifies the <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> object by sorting it according to
  520. the supplied criteria. The argument can be either a string or a SortKey
  521. enum identifying the basis of a sort (example: <code class="docutils literal notranslate"><span class="pre">'time'</span></code>, <code class="docutils literal notranslate"><span class="pre">'name'</span></code>,
  522. <code class="docutils literal notranslate"><span class="pre">SortKey.TIME</span></code> or <code class="docutils literal notranslate"><span class="pre">SortKey.NAME</span></code>). The SortKey enums argument have
  523. advantage over the string argument in that it is more robust and less
  524. error prone.</p>
  525. <p>When more than one key is provided, then additional keys are used as
  526. secondary criteria when there is equality in all keys selected before
  527. them. For example, <code class="docutils literal notranslate"><span class="pre">sort_stats(SortKey.NAME,</span> <span class="pre">SortKey.FILE)</span></code> will sort
  528. all the entries according to their function name, and resolve all ties
  529. (identical function names) by sorting by file name.</p>
  530. <p>For the string argument, abbreviations can be used for any key names, as
  531. long as the abbreviation is unambiguous.</p>
  532. <p>The following are the valid string and SortKey:</p>
  533. <table class="docutils align-default">
  534. <thead>
  535. <tr class="row-odd"><th class="head"><p>Valid String Arg</p></th>
  536. <th class="head"><p>Valid enum Arg</p></th>
  537. <th class="head"><p>Meaning</p></th>
  538. </tr>
  539. </thead>
  540. <tbody>
  541. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'calls'</span></code></p></td>
  542. <td><p>SortKey.CALLS</p></td>
  543. <td><p>call count</p></td>
  544. </tr>
  545. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'cumulative'</span></code></p></td>
  546. <td><p>SortKey.CUMULATIVE</p></td>
  547. <td><p>cumulative time</p></td>
  548. </tr>
  549. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'cumtime'</span></code></p></td>
  550. <td><p>N/A</p></td>
  551. <td><p>cumulative time</p></td>
  552. </tr>
  553. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'file'</span></code></p></td>
  554. <td><p>N/A</p></td>
  555. <td><p>file name</p></td>
  556. </tr>
  557. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'filename'</span></code></p></td>
  558. <td><p>SortKey.FILENAME</p></td>
  559. <td><p>file name</p></td>
  560. </tr>
  561. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'module'</span></code></p></td>
  562. <td><p>N/A</p></td>
  563. <td><p>file name</p></td>
  564. </tr>
  565. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'ncalls'</span></code></p></td>
  566. <td><p>N/A</p></td>
  567. <td><p>call count</p></td>
  568. </tr>
  569. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'pcalls'</span></code></p></td>
  570. <td><p>SortKey.PCALLS</p></td>
  571. <td><p>primitive call count</p></td>
  572. </tr>
  573. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'line'</span></code></p></td>
  574. <td><p>SortKey.LINE</p></td>
  575. <td><p>line number</p></td>
  576. </tr>
  577. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'name'</span></code></p></td>
  578. <td><p>SortKey.NAME</p></td>
  579. <td><p>function name</p></td>
  580. </tr>
  581. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'nfl'</span></code></p></td>
  582. <td><p>SortKey.NFL</p></td>
  583. <td><p>name/file/line</p></td>
  584. </tr>
  585. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'stdname'</span></code></p></td>
  586. <td><p>SortKey.STDNAME</p></td>
  587. <td><p>standard name</p></td>
  588. </tr>
  589. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">'time'</span></code></p></td>
  590. <td><p>SortKey.TIME</p></td>
  591. <td><p>internal time</p></td>
  592. </tr>
  593. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">'tottime'</span></code></p></td>
  594. <td><p>N/A</p></td>
  595. <td><p>internal time</p></td>
  596. </tr>
  597. </tbody>
  598. </table>
  599. <p>Note that all sorts on statistics are in descending order (placing most
  600. time consuming items first), where as name, file, and line number searches
  601. are in ascending order (alphabetical). The subtle distinction between
  602. <code class="docutils literal notranslate"><span class="pre">SortKey.NFL</span></code> and <code class="docutils literal notranslate"><span class="pre">SortKey.STDNAME</span></code> is that the standard name is a
  603. sort of the name as printed, which means that the embedded line numbers
  604. get compared in an odd way. For example, lines 3, 20, and 40 would (if
  605. the file names were the same) appear in the string order 20, 3 and 40.
  606. In contrast, <code class="docutils literal notranslate"><span class="pre">SortKey.NFL</span></code> does a numeric compare of the line numbers.
  607. In fact, <code class="docutils literal notranslate"><span class="pre">sort_stats(SortKey.NFL)</span></code> is the same as
  608. <code class="docutils literal notranslate"><span class="pre">sort_stats(SortKey.NAME,</span> <span class="pre">SortKey.FILENAME,</span> <span class="pre">SortKey.LINE)</span></code>.</p>
  609. <p>For backward-compatibility reasons, the numeric arguments <code class="docutils literal notranslate"><span class="pre">-1</span></code>, <code class="docutils literal notranslate"><span class="pre">0</span></code>,
  610. <code class="docutils literal notranslate"><span class="pre">1</span></code>, and <code class="docutils literal notranslate"><span class="pre">2</span></code> are permitted. They are interpreted as <code class="docutils literal notranslate"><span class="pre">'stdname'</span></code>,
  611. <code class="docutils literal notranslate"><span class="pre">'calls'</span></code>, <code class="docutils literal notranslate"><span class="pre">'time'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'cumulative'</span></code> respectively. If this old
  612. style format (numeric) is used, only one sort key (the numeric key) will
  613. be used, and additional arguments will be silently ignored.</p>
  614. <div class="versionadded">
  615. <p><span class="versionmodified added">New in version 3.7: </span>Added the SortKey enum.</p>
  616. </div>
  617. </dd></dl>
  618. <dl class="py method">
  619. <dt class="sig sig-object py" id="pstats.Stats.reverse_order">
  620. <span class="sig-name descname"><span class="pre">reverse_order</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pstats.Stats.reverse_order" title="Link to this definition">¶</a></dt>
  621. <dd><p>This method for the <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> class reverses the ordering of the
  622. basic list within the object. Note that by default ascending vs
  623. descending order is properly selected based on the sort key of choice.</p>
  624. </dd></dl>
  625. <dl class="py method">
  626. <dt class="sig sig-object py" id="pstats.Stats.print_stats">
  627. <span class="sig-name descname"><span class="pre">print_stats</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">restrictions</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pstats.Stats.print_stats" title="Link to this definition">¶</a></dt>
  628. <dd><p>This method for the <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> class prints out a report as described
  629. in the <a class="reference internal" href="#profile.run" title="profile.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">profile.run()</span></code></a> definition.</p>
  630. <p>The order of the printing is based on the last
  631. <a class="reference internal" href="#pstats.Stats.sort_stats" title="pstats.Stats.sort_stats"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sort_stats()</span></code></a> operation done on the object (subject to
  632. caveats in <a class="reference internal" href="#pstats.Stats.add" title="pstats.Stats.add"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code></a> and
  633. <a class="reference internal" href="#pstats.Stats.strip_dirs" title="pstats.Stats.strip_dirs"><code class="xref py py-meth docutils literal notranslate"><span class="pre">strip_dirs()</span></code></a>).</p>
  634. <p>The arguments provided (if any) can be used to limit the list down to the
  635. significant entries. Initially, the list is taken to be the complete set
  636. of profiled functions. Each restriction is either an integer (to select a
  637. count of lines), or a decimal fraction between 0.0 and 1.0 inclusive (to
  638. select a percentage of lines), or a string that will interpreted as a
  639. regular expression (to pattern match the standard name that is printed).
  640. If several restrictions are provided, then they are applied sequentially.
  641. For example:</p>
  642. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">print_stats</span><span class="p">(</span><span class="mf">.1</span><span class="p">,</span> <span class="s1">&#39;foo:&#39;</span><span class="p">)</span>
  643. </pre></div>
  644. </div>
  645. <p>would first limit the printing to first 10% of list, and then only print
  646. functions that were part of filename <code class="file docutils literal notranslate"><span class="pre">.*foo:</span></code>. In contrast, the
  647. command:</p>
  648. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">print_stats</span><span class="p">(</span><span class="s1">&#39;foo:&#39;</span><span class="p">,</span> <span class="mf">.1</span><span class="p">)</span>
  649. </pre></div>
  650. </div>
  651. <p>would limit the list to all functions having file names <code class="file docutils literal notranslate"><span class="pre">.*foo:</span></code>,
  652. and then proceed to only print the first 10% of them.</p>
  653. </dd></dl>
  654. <dl class="py method">
  655. <dt class="sig sig-object py" id="pstats.Stats.print_callers">
  656. <span class="sig-name descname"><span class="pre">print_callers</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">restrictions</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pstats.Stats.print_callers" title="Link to this definition">¶</a></dt>
  657. <dd><p>This method for the <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> class prints a list of all functions
  658. that called each function in the profiled database. The ordering is
  659. identical to that provided by <a class="reference internal" href="#pstats.Stats.print_stats" title="pstats.Stats.print_stats"><code class="xref py py-meth docutils literal notranslate"><span class="pre">print_stats()</span></code></a>, and the
  660. definition of the restricting argument is also identical. Each caller is
  661. reported on its own line. The format differs slightly depending on the
  662. profiler that produced the stats:</p>
  663. <ul class="simple">
  664. <li><p>With <a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a>, a number is shown in parentheses after each caller
  665. to show how many times this specific call was made. For convenience, a
  666. second non-parenthesized number repeats the cumulative time spent in the
  667. function at the right.</p></li>
  668. <li><p>With <a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a>, each caller is preceded by three numbers: the
  669. number of times this specific call was made, and the total and
  670. cumulative times spent in the current function while it was invoked by
  671. this specific caller.</p></li>
  672. </ul>
  673. </dd></dl>
  674. <dl class="py method">
  675. <dt class="sig sig-object py" id="pstats.Stats.print_callees">
  676. <span class="sig-name descname"><span class="pre">print_callees</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">restrictions</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pstats.Stats.print_callees" title="Link to this definition">¶</a></dt>
  677. <dd><p>This method for the <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> class prints a list of all function
  678. that were called by the indicated function. Aside from this reversal of
  679. direction of calls (re: called vs was called by), the arguments and
  680. ordering are identical to the <a class="reference internal" href="#pstats.Stats.print_callers" title="pstats.Stats.print_callers"><code class="xref py py-meth docutils literal notranslate"><span class="pre">print_callers()</span></code></a> method.</p>
  681. </dd></dl>
  682. <dl class="py method">
  683. <dt class="sig sig-object py" id="pstats.Stats.get_stats_profile">
  684. <span class="sig-name descname"><span class="pre">get_stats_profile</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pstats.Stats.get_stats_profile" title="Link to this definition">¶</a></dt>
  685. <dd><p>This method returns an instance of StatsProfile, which contains a mapping
  686. of function names to instances of FunctionProfile. Each FunctionProfile
  687. instance holds information related to the function’s profile such as how
  688. long the function took to run, how many times it was called, etc…</p>
  689. <div class="versionadded">
  690. <p><span class="versionmodified added">New in version 3.9: </span>Added the following dataclasses: StatsProfile, FunctionProfile.
  691. Added the following function: get_stats_profile.</p>
  692. </div>
  693. </dd></dl>
  694. </dd></dl>
  695. </section>
  696. <section id="what-is-deterministic-profiling">
  697. <span id="deterministic-profiling"></span><h2>What Is Deterministic Profiling?<a class="headerlink" href="#what-is-deterministic-profiling" title="Link to this heading">¶</a></h2>
  698. <p><em class="dfn">Deterministic profiling</em> is meant to reflect the fact that all <em>function
  699. call</em>, <em>function return</em>, and <em>exception</em> events are monitored, and precise
  700. timings are made for the intervals between these events (during which time the
  701. user’s code is executing). In contrast, <em class="dfn">statistical profiling</em> (which is
  702. not done by this module) randomly samples the effective instruction pointer, and
  703. deduces where time is being spent. The latter technique traditionally involves
  704. less overhead (as the code does not need to be instrumented), but provides only
  705. relative indications of where time is being spent.</p>
  706. <p>In Python, since there is an interpreter active during execution, the presence
  707. of instrumented code is not required in order to do deterministic profiling.
  708. Python automatically provides a <em class="dfn">hook</em> (optional callback) for each event.
  709. In addition, the interpreted nature of Python tends to add so much overhead to
  710. execution, that deterministic profiling tends to only add small processing
  711. overhead in typical applications. The result is that deterministic profiling is
  712. not that expensive, yet provides extensive run time statistics about the
  713. execution of a Python program.</p>
  714. <p>Call count statistics can be used to identify bugs in code (surprising counts),
  715. and to identify possible inline-expansion points (high call counts). Internal
  716. time statistics can be used to identify “hot loops” that should be carefully
  717. optimized. Cumulative time statistics should be used to identify high level
  718. errors in the selection of algorithms. Note that the unusual handling of
  719. cumulative times in this profiler allows statistics for recursive
  720. implementations of algorithms to be directly compared to iterative
  721. implementations.</p>
  722. </section>
  723. <section id="limitations">
  724. <span id="profile-limitations"></span><h2>Limitations<a class="headerlink" href="#limitations" title="Link to this heading">¶</a></h2>
  725. <p>One limitation has to do with accuracy of timing information. There is a
  726. fundamental problem with deterministic profilers involving accuracy. The most
  727. obvious restriction is that the underlying “clock” is only ticking at a rate
  728. (typically) of about .001 seconds. Hence no measurements will be more accurate
  729. than the underlying clock. If enough measurements are taken, then the “error”
  730. will tend to average out. Unfortunately, removing this first error induces a
  731. second source of error.</p>
  732. <p>The second problem is that it “takes a while” from when an event is dispatched
  733. until the profiler’s call to get the time actually <em>gets</em> the state of the
  734. clock. Similarly, there is a certain lag when exiting the profiler event
  735. handler from the time that the clock’s value was obtained (and then squirreled
  736. away), until the user’s code is once again executing. As a result, functions
  737. that are called many times, or call many functions, will typically accumulate
  738. this error. The error that accumulates in this fashion is typically less than
  739. the accuracy of the clock (less than one clock tick), but it <em>can</em> accumulate
  740. and become very significant.</p>
  741. <p>The problem is more important with <a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> than with the lower-overhead
  742. <a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a>. For this reason, <a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> provides a means of
  743. calibrating itself for a given platform so that this error can be
  744. probabilistically (on the average) removed. After the profiler is calibrated, it
  745. will be more accurate (in a least square sense), but it will sometimes produce
  746. negative numbers (when call counts are exceptionally low, and the gods of
  747. probability work against you :-). ) Do <em>not</em> be alarmed by negative numbers in
  748. the profile. They should <em>only</em> appear if you have calibrated your profiler,
  749. and the results are actually better than without calibration.</p>
  750. </section>
  751. <section id="calibration">
  752. <span id="profile-calibration"></span><h2>Calibration<a class="headerlink" href="#calibration" title="Link to this heading">¶</a></h2>
  753. <p>The profiler of the <a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> module subtracts a constant from each event
  754. handling time to compensate for the overhead of calling the time function, and
  755. socking away the results. By default, the constant is 0. The following
  756. procedure can be used to obtain a better constant for a given platform (see
  757. <a class="reference internal" href="#profile-limitations"><span class="std std-ref">Limitations</span></a>).</p>
  758. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">profile</span>
  759. <span class="n">pr</span> <span class="o">=</span> <span class="n">profile</span><span class="o">.</span><span class="n">Profile</span><span class="p">()</span>
  760. <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">):</span>
  761. <span class="nb">print</span><span class="p">(</span><span class="n">pr</span><span class="o">.</span><span class="n">calibrate</span><span class="p">(</span><span class="mi">10000</span><span class="p">))</span>
  762. </pre></div>
  763. </div>
  764. <p>The method executes the number of Python calls given by the argument, directly
  765. and again under the profiler, measuring the time for both. It then computes the
  766. hidden overhead per profiler event, and returns that as a float. For example,
  767. on a 1.8Ghz Intel Core i5 running macOS, and using Python’s time.process_time() as
  768. the timer, the magical number is about 4.04e-6.</p>
  769. <p>The object of this exercise is to get a fairly consistent result. If your
  770. computer is <em>very</em> fast, or your timer function has poor resolution, you might
  771. have to pass 100000, or even 1000000, to get consistent results.</p>
  772. <p>When you have a consistent answer, there are three ways you can use it:</p>
  773. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">profile</span>
  774. <span class="c1"># 1. Apply computed bias to all Profile instances created hereafter.</span>
  775. <span class="n">profile</span><span class="o">.</span><span class="n">Profile</span><span class="o">.</span><span class="n">bias</span> <span class="o">=</span> <span class="n">your_computed_bias</span>
  776. <span class="c1"># 2. Apply computed bias to a specific Profile instance.</span>
  777. <span class="n">pr</span> <span class="o">=</span> <span class="n">profile</span><span class="o">.</span><span class="n">Profile</span><span class="p">()</span>
  778. <span class="n">pr</span><span class="o">.</span><span class="n">bias</span> <span class="o">=</span> <span class="n">your_computed_bias</span>
  779. <span class="c1"># 3. Specify computed bias in instance constructor.</span>
  780. <span class="n">pr</span> <span class="o">=</span> <span class="n">profile</span><span class="o">.</span><span class="n">Profile</span><span class="p">(</span><span class="n">bias</span><span class="o">=</span><span class="n">your_computed_bias</span><span class="p">)</span>
  781. </pre></div>
  782. </div>
  783. <p>If you have a choice, you are better off choosing a smaller constant, and then
  784. your results will “less often” show up as negative in profile statistics.</p>
  785. </section>
  786. <section id="using-a-custom-timer">
  787. <span id="profile-timers"></span><h2>Using a custom timer<a class="headerlink" href="#using-a-custom-timer" title="Link to this heading">¶</a></h2>
  788. <p>If you want to change how current time is determined (for example, to force use
  789. of wall-clock time or elapsed process time), pass the timing function you want
  790. to the <code class="xref py py-class docutils literal notranslate"><span class="pre">Profile</span></code> class constructor:</p>
  791. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">pr</span> <span class="o">=</span> <span class="n">profile</span><span class="o">.</span><span class="n">Profile</span><span class="p">(</span><span class="n">your_time_func</span><span class="p">)</span>
  792. </pre></div>
  793. </div>
  794. <p>The resulting profiler will then call <code class="docutils literal notranslate"><span class="pre">your_time_func</span></code>. Depending on whether
  795. you are using <a class="reference internal" href="#profile.Profile" title="profile.Profile"><code class="xref py py-class docutils literal notranslate"><span class="pre">profile.Profile</span></code></a> or <code class="xref py py-class docutils literal notranslate"><span class="pre">cProfile.Profile</span></code>,
  796. <code class="docutils literal notranslate"><span class="pre">your_time_func</span></code>’s return value will be interpreted differently:</p>
  797. <dl>
  798. <dt><a class="reference internal" href="#profile.Profile" title="profile.Profile"><code class="xref py py-class docutils literal notranslate"><span class="pre">profile.Profile</span></code></a></dt><dd><p><code class="docutils literal notranslate"><span class="pre">your_time_func</span></code> should return a single number, or a list of numbers whose
  799. sum is the current time (like what <a class="reference internal" href="os.html#os.times" title="os.times"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.times()</span></code></a> returns). If the
  800. function returns a single time number, or the list of returned numbers has
  801. length 2, then you will get an especially fast version of the dispatch
  802. routine.</p>
  803. <p>Be warned that you should calibrate the profiler class for the timer function
  804. that you choose (see <a class="reference internal" href="#profile-calibration"><span class="std std-ref">Calibration</span></a>). For most machines, a timer
  805. that returns a lone integer value will provide the best results in terms of
  806. low overhead during profiling. (<a class="reference internal" href="os.html#os.times" title="os.times"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.times()</span></code></a> is <em>pretty</em> bad, as it
  807. returns a tuple of floating point values). If you want to substitute a
  808. better timer in the cleanest fashion, derive a class and hardwire a
  809. replacement dispatch method that best handles your timer call, along with the
  810. appropriate calibration constant.</p>
  811. </dd>
  812. <dt><code class="xref py py-class docutils literal notranslate"><span class="pre">cProfile.Profile</span></code></dt><dd><p><code class="docutils literal notranslate"><span class="pre">your_time_func</span></code> should return a single number. If it returns integers,
  813. you can also invoke the class constructor with a second argument specifying
  814. the real duration of one unit of time. For example, if
  815. <code class="docutils literal notranslate"><span class="pre">your_integer_time_func</span></code> returns times measured in thousands of seconds,
  816. you would construct the <code class="xref py py-class docutils literal notranslate"><span class="pre">Profile</span></code> instance as follows:</p>
  817. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">pr</span> <span class="o">=</span> <span class="n">cProfile</span><span class="o">.</span><span class="n">Profile</span><span class="p">(</span><span class="n">your_integer_time_func</span><span class="p">,</span> <span class="mf">0.001</span><span class="p">)</span>
  818. </pre></div>
  819. </div>
  820. <p>As the <code class="xref py py-class docutils literal notranslate"><span class="pre">cProfile.Profile</span></code> class cannot be calibrated, custom timer
  821. functions should be used with care and should be as fast as possible. For
  822. the best results with a custom timer, it might be necessary to hard-code it
  823. in the C source of the internal <code class="xref py py-mod docutils literal notranslate"><span class="pre">_lsprof</span></code> module.</p>
  824. </dd>
  825. </dl>
  826. <p>Python 3.3 adds several new functions in <a class="reference internal" href="time.html#module-time" title="time: Time access and conversions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code></a> that can be used to make
  827. precise measurements of process or wall-clock time. For example, see
  828. <a class="reference internal" href="time.html#time.perf_counter" title="time.perf_counter"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.perf_counter()</span></code></a>.</p>
  829. </section>
  830. </section>
  831. <div class="clearer"></div>
  832. </div>
  833. </div>
  834. </div>
  835. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  836. <div class="sphinxsidebarwrapper">
  837. <div>
  838. <h3><a href="../contents.html">Table of Contents</a></h3>
  839. <ul>
  840. <li><a class="reference internal" href="#">The Python Profilers</a><ul>
  841. <li><a class="reference internal" href="#introduction-to-the-profilers">Introduction to the profilers</a></li>
  842. <li><a class="reference internal" href="#instant-user-s-manual">Instant User’s Manual</a></li>
  843. <li><a class="reference internal" href="#module-cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code> Module Reference</a></li>
  844. <li><a class="reference internal" href="#the-stats-class">The <code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code> Class</a></li>
  845. <li><a class="reference internal" href="#what-is-deterministic-profiling">What Is Deterministic Profiling?</a></li>
  846. <li><a class="reference internal" href="#limitations">Limitations</a></li>
  847. <li><a class="reference internal" href="#calibration">Calibration</a></li>
  848. <li><a class="reference internal" href="#using-a-custom-timer">Using a custom timer</a></li>
  849. </ul>
  850. </li>
  851. </ul>
  852. </div>
  853. <div>
  854. <h4>Previous topic</h4>
  855. <p class="topless"><a href="pdb.html"
  856. title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pdb</span></code> — The Python Debugger</a></p>
  857. </div>
  858. <div>
  859. <h4>Next topic</h4>
  860. <p class="topless"><a href="timeit.html"
  861. title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">timeit</span></code> — Measure execution time of small code snippets</a></p>
  862. </div>
  863. <div role="note" aria-label="source link">
  864. <h3>This Page</h3>
  865. <ul class="this-page-menu">
  866. <li><a href="../bugs.html">Report a Bug</a></li>
  867. <li>
  868. <a href="https://github.com/python/cpython/blob/main/Doc/library/profile.rst"
  869. rel="nofollow">Show Source
  870. </a>
  871. </li>
  872. </ul>
  873. </div>
  874. </div>
  875. <div id="sidebarbutton" title="Collapse sidebar">
  876. <span>«</span>
  877. </div>
  878. </div>
  879. <div class="clearer"></div>
  880. </div>
  881. <div class="related" role="navigation" aria-label="related navigation">
  882. <h3>Navigation</h3>
  883. <ul>
  884. <li class="right" style="margin-right: 10px">
  885. <a href="../genindex.html" title="General Index"
  886. >index</a></li>
  887. <li class="right" >
  888. <a href="../py-modindex.html" title="Python Module Index"
  889. >modules</a> |</li>
  890. <li class="right" >
  891. <a href="timeit.html" title="timeit — Measure execution time of small code snippets"
  892. >next</a> |</li>
  893. <li class="right" >
  894. <a href="pdb.html" title="pdb — The Python Debugger"
  895. >previous</a> |</li>
  896. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  897. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  898. <li class="switchers">
  899. <div class="language_switcher_placeholder"></div>
  900. <div class="version_switcher_placeholder"></div>
  901. </li>
  902. <li>
  903. </li>
  904. <li id="cpython-language-and-version">
  905. <a href="../index.html">3.12.3 Documentation</a> &#187;
  906. </li>
  907. <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
  908. <li class="nav-item nav-item-2"><a href="debug.html" >Debugging and Profiling</a> &#187;</li>
  909. <li class="nav-item nav-item-this"><a href="">The Python Profilers</a></li>
  910. <li class="right">
  911. <div class="inline-search" role="search">
  912. <form class="inline-search" action="../search.html" method="get">
  913. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  914. <input type="submit" value="Go" />
  915. </form>
  916. </div>
  917. |
  918. </li>
  919. <li class="right">
  920. <label class="theme-selector-label">
  921. Theme
  922. <select class="theme-selector" oninput="activateTheme(this.value)">
  923. <option value="auto" selected>Auto</option>
  924. <option value="light">Light</option>
  925. <option value="dark">Dark</option>
  926. </select>
  927. </label> |</li>
  928. </ul>
  929. </div>
  930. <div class="footer">
  931. &copy;
  932. <a href="../copyright.html">
  933. Copyright
  934. </a>
  935. 2001-2024, Python Software Foundation.
  936. <br />
  937. This page is licensed under the Python Software Foundation License Version 2.
  938. <br />
  939. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  940. <br />
  941. See <a href="/license.html">History and License</a> for more information.<br />
  942. <br />
  943. The Python Software Foundation is a non-profit corporation.
  944. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  945. <br />
  946. <br />
  947. Last updated on Apr 09, 2024 (13:47 UTC).
  948. <a href="/bugs.html">Found a bug</a>?
  949. <br />
  950. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 7.2.6.
  951. </div>
  952. </body>
  953. </html>
上海开阖软件有限公司 沪ICP备12045867号-1