Team Ai
Apppublic

parthtamu/rag-code-assistant

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
profiling.tracing.html696 linesDownload Raw Back to docs
1<!DOCTYPE html>2 3<html lang="en" data-content_root="../">4  <head>5    <meta charset="utf-8" />6    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />7<meta property="og:title" content="profiling.tracing — Deterministic profiler" />8<meta property="og:type" content="website" />9<meta property="og:url" content="https://docs.python.org/3/library/profiling.tracing.html" />10<meta property="og:site_name" content="Python documentation" />11<meta property="og:description" content="Source code: Lib/profiling/tracing/ The profiling.tracing module provides deterministic profiling of Python programs. It monitors every function call, function return, and exception event, recordin..." />12<meta property="og:image:width" content="1146" />13<meta property="og:image:height" content="600" />14<meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_profiling.tracing_c6651177.png" />15<meta property="og:image:alt" content="Source code: Lib/profiling/tracing/ The profiling.tracing module provides deterministic profiling of Python programs. It monitors every function call, function return, and exception event, recordin..." />16<meta name="description" content="Source code: Lib/profiling/tracing/ The profiling.tracing module provides deterministic profiling of Python programs. It monitors every function call, function return, and exception event, recordin..." />17<meta name="twitter:card" content="summary_large_image" />18<meta name="theme-color" content="#3776ab">19 20    <title>profiling.tracing — Deterministic profiler &#8212; Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">21    22    <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />23    <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" />24    <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" />25    <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" />26    <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />27    28    <script src="../_static/documentation_options.js?v=6b7c9ff5"></script>29    <script src="../_static/doctools.js?v=9bcbadda"></script>30    <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>31    <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script>32    33    <script src="../_static/sidebar.js"></script>34    35    <link rel="search" type="application/opensearchdescription+xml"36          title="Search within Python 3.15.0a6 documentation"37          href="../_static/opensearch.xml"/>38    <link rel="author" title="About these documents" href="../about.html" />39    <link rel="index" title="Index" href="../genindex.html" />40    <link rel="search" title="Search" href="../search.html" />41    <link rel="copyright" title="Copyright" href="../copyright.html" />42    <link rel="next" title="profiling.sampling — Statistical profiler" href="profiling.sampling.html" />43    <link rel="prev" title="profiling — Python profilers" href="profiling.html" />44    45      46      <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script>47      48      <link rel="canonical" href="https://docs.python.org/3/library/profiling.tracing.html">49      50    51 52    53    <style>54      @media only screen {55        table.full-width-table {56            width: 100%;57        }58      }59    </style>60<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">61    <link rel="shortcut icon" type="image/png" href="../_static/py.svg">62            <script type="text/javascript" src="../_static/copybutton.js"></script>63            <script type="text/javascript" src="../_static/menu.js"></script>64            <script type="text/javascript" src="../_static/search-focus.js"></script>65            <script type="text/javascript" src="../_static/themetoggle.js"></script> 66            <script type="text/javascript" src="../_static/rtd_switcher.js"></script>67            <meta name="readthedocs-addons-api-version" content="1">68 69  </head>70<body>71<div class="mobile-nav">72    <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"73           aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu">74    <nav class="nav-content" role="navigation">75        <label for="menuToggler" class="toggler__label">76            <span></span>77        </label>78        <span class="nav-items-wrapper">79            <a href="https://www.python.org/" class="nav-logo">80                <img src="../_static/py.svg" alt="Python logo">81            </a>82            <span class="version_switcher_placeholder"></span>83            <form role="search" class="search" action="../search.html" method="get">84                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">85                    <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>86                </svg>87                <input placeholder="Quick search" aria-label="Quick search" type="search" name="q">88                <input type="submit" value="Go">89            </form>90        </span>91    </nav>92    <div class="menu-wrapper">93        <nav class="menu" role="navigation" aria-label="main navigation">94            <div class="language_switcher_placeholder"></div>95            96<label class="theme-selector-label">97    Theme98    <select class="theme-selector" oninput="activateTheme(this.value)">99        <option value="auto" selected>Auto</option>100        <option value="light">Light</option>101        <option value="dark">Dark</option>102    </select>103</label>104  <div>105    <h3><a href="../contents.html">Table of Contents</a></h3>106    <ul>107<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">profiling.tracing</span></code> — Deterministic profiler</a><ul>108<li><a class="reference internal" href="#what-is-deterministic-profiling">What is deterministic profiling?</a></li>109<li><a class="reference internal" href="#command-line-interface">Command-line interface</a></li>110<li><a class="reference internal" href="#programmatic-usage-examples">Programmatic usage examples</a><ul>111<li><a class="reference internal" href="#basic-profiling">Basic profiling</a></li>112<li><a class="reference internal" href="#using-the-profile-class">Using the <code class="xref py py-class docutils literal notranslate"><span class="pre">Profile</span></code> class</a></li>113</ul>114</li>115<li><a class="reference internal" href="#module-reference">Module reference</a></li>116<li><a class="reference internal" href="#using-a-custom-timer">Using a custom timer</a></li>117<li><a class="reference internal" href="#limitations">Limitations</a></li>118</ul>119</li>120</ul>121 122  </div>123  <div>124    <h4>Previous topic</h4>125    <p class="topless"><a href="profiling.html"126                          title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">profiling</span></code> — Python profilers</a></p>127  </div>128  <div>129    <h4>Next topic</h4>130    <p class="topless"><a href="profiling.sampling.html"131                          title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">profiling.sampling</span></code> — Statistical profiler</a></p>132  </div>133  <script>134    document.addEventListener('DOMContentLoaded', () => {135        const title = document.querySelector('meta[property="og:title"]').content;136        const elements = document.querySelectorAll('.improvepage');137        const pageurl = window.location.href.split('?')[0];138        elements.forEach(element => {139            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));140            url.searchParams.set('pagetitle', title);141            url.searchParams.set('pageurl', pageurl);142            url.searchParams.set('pagesource', "library/profiling.tracing.rst");143            element.href = url.toString();144        });145    });146  </script>147  <div role="note" aria-label="source link">148    <h3>This page</h3>149    <ul class="this-page-menu">150      <li><a href="../bugs.html">Report a bug</a></li>151      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>152      <li>153        <a href="https://github.com/python/cpython/blob/main/Doc/library/profiling.tracing.rst?plain=1"154            rel="nofollow">Show source155        </a>156      </li>157      158    </ul>159  </div>160        </nav>161    </div>162</div>163 164  165    <div class="related" role="navigation" aria-label="Related">166      <h3>Navigation</h3>167      <ul>168        <li class="right" style="margin-right: 10px">169          <a href="../genindex.html" title="General Index"170             accesskey="I">index</a></li>171        <li class="right" >172          <a href="../py-modindex.html" title="Python Module Index"173             >modules</a> |</li>174        <li class="right" >175          <a href="profiling.sampling.html" title="profiling.sampling — Statistical profiler"176             accesskey="N">next</a> |</li>177        <li class="right" >178          <a href="profiling.html" title="profiling — Python profilers"179             accesskey="P">previous</a> |</li>180 181          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>182          <li><a href="https://www.python.org/">Python</a> &#187;</li>183          <li class="switchers">184            <div class="language_switcher_placeholder"></div>185            <div class="version_switcher_placeholder"></div>186          </li>187          <li>188              189          </li>190    <li id="cpython-language-and-version">191      <a href="../index.html">3.15.0a6 Documentation</a> &#187;192    </li>193 194          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>195          <li class="nav-item nav-item-2"><a href="debug.html" >Debugging and profiling</a> &#187;</li>196          <li class="nav-item nav-item-3"><a href="profiling.html" accesskey="U"><code class="xref py py-mod docutils literal notranslate"><span class="pre">profiling</span></code> — Python profilers</a> &#187;</li>197        <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">profiling.tracing</span></code> — Deterministic profiler</a></li>198                <li class="right">199                    200 201    <div class="inline-search" role="search">202        <form class="inline-search" action="../search.html" method="get">203          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">204          <input type="submit" value="Go">205        </form>206    </div>207                     |208                </li>209            <li class="right">210<label class="theme-selector-label">211    Theme212    <select class="theme-selector" oninput="activateTheme(this.value)">213        <option value="auto" selected>Auto</option>214        <option value="light">Light</option>215        <option value="dark">Dark</option>216    </select>217</label> |</li>218            219      </ul>220    </div>    221 222    <div class="document">223      <div class="documentwrapper">224        <div class="bodywrapper">225          <div class="body" role="main">226            227  <section id="module-profiling.tracing">228<span id="profiling-tracing-deterministic-profiler"></span><span id="profiling-tracing"></span><h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">profiling.tracing</span></code> — Deterministic profiler<a class="headerlink" href="#module-profiling.tracing" title="Link to this heading">¶</a></h1>229<div class="versionadded">230<p><span class="versionmodified added">Added in version 3.15.</span></p>231</div>232<p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/profiling/tracing/">Lib/profiling/tracing/</a></p>233<hr class="docutils" />234<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">profiling.tracing</span></code> module provides deterministic profiling of Python235programs. It monitors every function call, function return, and exception event,236recording precise timing for each. This approach provides exact call counts and237complete visibility into program execution, making it ideal for development and238testing scenarios.</p>239<div class="admonition note">240<p class="admonition-title">Note</p>241<p>This module is also available as <code class="docutils literal notranslate"><span class="pre">cProfile</span></code> for backward compatibility.242The <code class="docutils literal notranslate"><span class="pre">cProfile</span></code> name will continue to work in all future Python versions.243Use whichever import style suits your codebase:</p>244<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Preferred (new style)</span>245<span class="kn">import</span><span class="w"> </span><span class="nn">profiling.tracing</span>246<span class="n">profiling</span><span class="o">.</span><span class="n">tracing</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="s1">&#39;my_function()&#39;</span><span class="p">)</span>247 248<span class="c1"># Also works (backward compatible)</span>249<span class="kn">import</span><span class="w"> </span><span class="nn">cProfile</span>250<span class="n">cProfile</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="s1">&#39;my_function()&#39;</span><span class="p">)</span>251</pre></div>252</div>253</div>254<section id="what-is-deterministic-profiling">255<h2>What is deterministic profiling?<a class="headerlink" href="#what-is-deterministic-profiling" title="Link to this heading">¶</a></h2>256<p><em class="dfn">Deterministic profiling</em> captures every function call, function return,257and exception event during program execution. The profiler measures the precise258time intervals between these events, providing exact statistics about how the259program behaves.</p>260<p>In contrast to <a class="reference internal" href="profiling.sampling.html#profiling-sampling"><span class="std std-ref">statistical profiling</span></a>, which samples261the call stack periodically to estimate where time is spent, deterministic262profiling records every event. This means you get exact call counts rather than263statistical approximations. The trade-off is that instrumenting every event264introduces overhead that can slow down program execution.</p>265<p>Python’s interpreted nature makes deterministic profiling practical. The266interpreter already dispatches events for function calls and returns, so the267profiler can hook into this mechanism without requiring code modification. The268overhead tends to be moderate relative to the inherent cost of interpretation,269making deterministic profiling suitable for most development workflows.</p>270<p>Deterministic profiling helps answer questions like:</p>271<ul class="simple">272<li><p>How many times was this function called?</p></li>273<li><p>What is the complete call graph of my program?</p></li>274<li><p>Which functions are called by a particular function?</p></li>275<li><p>Are there unexpected function calls happening?</p></li>276</ul>277<p>Call count statistics can identify bugs (surprising counts) and inline278expansion opportunities (high call counts). Internal time statistics reveal279“hot loops” that warrant optimization. Cumulative time statistics help identify280algorithmic inefficiencies. The handling of cumulative times in this profiler281allows direct comparison of recursive and iterative implementations.</p>282</section>283<section id="command-line-interface">284<span id="profiling-tracing-cli"></span><h2>Command-line interface<a class="headerlink" href="#command-line-interface" title="Link to this heading">¶</a></h2>285<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">profiling.tracing</span></code> module can be invoked as a script to profile286another script or module:</p>287<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="go">python -m profiling.tracing [-o output_file] [-s sort_order] (-m module | script.py)</span>288</pre></div>289</div>290<p>This runs the specified script or module under the profiler and prints the291results to standard output (or saves them to a file).</p>292<dl class="std option">293<dt class="sig sig-object std" id="cmdoption-profiling.tracing-o">294<span class="sig-name descname"><span class="pre">-o</span></span><span class="sig-prename descclassname"> <span class="pre">&lt;output_file&gt;</span></span><a class="headerlink" href="#cmdoption-profiling.tracing-o" title="Link to this definition">¶</a></dt>295<dd><p>Write the profile results to a file instead of standard output. The output296file can be read by the <a class="reference internal" href="pstats.html#module-pstats" title="pstats: Statistics object for analyzing profiler output."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pstats</span></code></a> module for later analysis.</p>297</dd></dl>298 299<dl class="std option">300<dt class="sig sig-object std" id="cmdoption-profiling.tracing-s">301<span class="sig-name descname"><span class="pre">-s</span></span><span class="sig-prename descclassname"> <span class="pre">&lt;sort_order&gt;</span></span><a class="headerlink" href="#cmdoption-profiling.tracing-s" title="Link to this definition">¶</a></dt>302<dd><p>Sort the output by the specified key. This accepts any of the sort keys303recognized by <a class="reference internal" href="pstats.html#pstats.Stats.sort_stats" title="pstats.Stats.sort_stats"><code class="xref py py-meth docutils literal notranslate"><span class="pre">pstats.Stats.sort_stats()</span></code></a>, such as <code class="docutils literal notranslate"><span class="pre">cumulative</span></code>,304<code class="docutils literal notranslate"><span class="pre">time</span></code>, <code class="docutils literal notranslate"><span class="pre">calls</span></code>, or <code class="docutils literal notranslate"><span class="pre">name</span></code>. This option only applies when305<a class="reference internal" href="#cmdoption-profiling.tracing-o"><code class="xref std std-option docutils literal notranslate"><span class="pre">-o</span></code></a> is not specified.</p>306</dd></dl>307 308<dl class="std option">309<dt class="sig sig-object std" id="cmdoption-profiling.tracing-m">310<span class="sig-name descname"><span class="pre">-m</span></span><span class="sig-prename descclassname"> <span class="pre">&lt;module&gt;</span></span><a class="headerlink" href="#cmdoption-profiling.tracing-m" title="Link to this definition">¶</a></dt>311<dd><p>Profile a module instead of a script. The module is located using the312standard import mechanism.</p>313<div class="versionadded">314<p><span class="versionmodified added">Added in version 3.7: </span>The <code class="docutils literal notranslate"><span class="pre">-m</span></code> option for <code class="docutils literal notranslate"><span class="pre">cProfile</span></code>.</p>315</div>316<div class="versionadded">317<p><span class="versionmodified added">Added in version 3.8: </span>The <code class="docutils literal notranslate"><span class="pre">-m</span></code> option for <a class="reference internal" href="profile.html#module-profile" title="profile: Pure Python profiler (deprecated). (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a>.</p>318</div>319</dd></dl>320 321</section>322<section id="programmatic-usage-examples">323<h2>Programmatic usage examples<a class="headerlink" href="#programmatic-usage-examples" title="Link to this heading">¶</a></h2>324<p>For more control over profiling, use the module’s functions and classes325directly.</p>326<section id="basic-profiling">327<h3>Basic profiling<a class="headerlink" href="#basic-profiling" title="Link to this heading">¶</a></h3>328<p>The simplest approach uses the <code class="xref py py-func docutils literal notranslate"><span class="pre">run()</span></code> function:</p>329<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">profiling.tracing</span>330<span class="n">profiling</span><span class="o">.</span><span class="n">tracing</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="s1">&#39;my_function()&#39;</span><span class="p">)</span>331</pre></div>332</div>333<p>This profiles the given code string and prints a summary to standard output.334To save results for later analysis:</p>335<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">profiling</span><span class="o">.</span><span class="n">tracing</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="s1">&#39;my_function()&#39;</span><span class="p">,</span> <span class="s1">&#39;output.prof&#39;</span><span class="p">)</span>336</pre></div>337</div>338</section>339<section id="using-the-profile-class">340<h3>Using the <code class="xref py py-class docutils literal notranslate"><span class="pre">Profile</span></code> class<a class="headerlink" href="#using-the-profile-class" title="Link to this heading">¶</a></h3>341<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Profile</span></code> class provides fine-grained control:</p>342<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">profiling.tracing</span>343<span class="kn">import</span><span class="w"> </span><span class="nn">pstats</span>344<span class="kn">from</span><span class="w"> </span><span class="nn">io</span><span class="w"> </span><span class="kn">import</span> <span class="n">StringIO</span>345 346<span class="n">pr</span> <span class="o">=</span> <span class="n">profiling</span><span class="o">.</span><span class="n">tracing</span><span class="o">.</span><span class="n">Profile</span><span class="p">()</span>347<span class="n">pr</span><span class="o">.</span><span class="n">enable</span><span class="p">()</span>348<span class="c1"># ... code to profile ...</span>349<span class="n">pr</span><span class="o">.</span><span class="n">disable</span><span class="p">()</span>350 351<span class="c1"># Print results</span>352<span class="n">s</span> <span class="o">=</span> <span class="n">StringIO</span><span class="p">()</span>353<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">pstats</span><span class="o">.</span><span class="n">SortKey</span><span class="o">.</span><span class="n">CUMULATIVE</span><span class="p">)</span>354<span class="n">ps</span><span class="o">.</span><span class="n">print_stats</span><span class="p">()</span>355<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>356</pre></div>357</div>358<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Profile</span></code> class also works as a context manager:</p>359<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">profiling.tracing</span>360 361<span class="k">with</span> <span class="n">profiling</span><span class="o">.</span><span class="n">tracing</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>362    <span class="c1"># ... code to profile ...</span>363 364<span class="n">pr</span><span class="o">.</span><span class="n">print_stats</span><span class="p">()</span>365</pre></div>366</div>367</section>368</section>369<section id="module-reference">370<h2>Module reference<a class="headerlink" href="#module-reference" title="Link to this heading">¶</a></h2>371<dl class="py function">372<dt class="sig sig-object py" id="profiling.tracing.run">373<span class="sig-prename descclassname"><span class="pre">profiling.tracing.</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="#profiling.tracing.run" title="Link to this definition">¶</a></dt>374<dd><p>Profile execution of a command and print or save the results.</p>375<p>This function executes the <em>command</em> string using <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> in the376<code class="docutils literal notranslate"><span class="pre">__main__</span></code> module’s namespace:</p>377<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>378</pre></div>379</div>380<p>If <em>filename</em> is not provided, the function creates a <a class="reference internal" href="pstats.html#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">pstats.Stats</span></code></a>381instance and prints a summary to standard output. If <em>filename</em> is382provided, the raw profile data is saved to that file for later analysis383with <a class="reference internal" href="pstats.html#module-pstats" title="pstats: Statistics object for analyzing profiler output."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pstats</span></code></a>.</p>384<p>The <em>sort</em> argument specifies the sort order for printed output, accepting385any value recognized by <a class="reference internal" href="pstats.html#pstats.Stats.sort_stats" title="pstats.Stats.sort_stats"><code class="xref py py-meth docutils literal notranslate"><span class="pre">pstats.Stats.sort_stats()</span></code></a>.</p>386</dd></dl>387 388<dl class="py function">389<dt class="sig sig-object py" id="profiling.tracing.runctx">390<span class="sig-prename descclassname"><span class="pre">profiling.tracing.</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="#profiling.tracing.runctx" title="Link to this definition">¶</a></dt>391<dd><p>Profile execution of a command with explicit namespaces.</p>392<p>Like <a class="reference internal" href="#profiling.tracing.run" title="profiling.tracing.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">run()</span></code></a>, but executes the command with the specified <em>globals</em>393and <em>locals</em> mappings instead of using the <code class="docutils literal notranslate"><span class="pre">__main__</span></code> module’s namespace:</p>394<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>395</pre></div>396</div>397</dd></dl>398 399<dl class="py class">400<dt class="sig sig-object py" id="profiling.tracing.Profile">401<em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">profiling.tracing.</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="#profiling.tracing.Profile" title="Link to this definition">¶</a></dt>402<dd><p>A profiler object that collects execution statistics.</p>403<p>The optional <em>timer</em> argument specifies a custom timing function. If not404provided, the profiler uses a platform-appropriate default timer. When405supplying a custom timer, it must return a single number representing the406current time. If the timer returns integers, use <em>timeunit</em> to specify the407duration of one time unit (for example, <code class="docutils literal notranslate"><span class="pre">0.001</span></code> for milliseconds).</p>408<p>The <em>subcalls</em> argument controls whether the profiler tracks call409relationships between functions. The <em>builtins</em> argument controls whether410built-in functions are profiled.</p>411<div class="versionchanged">412<p><span class="versionmodified changed">Changed in version 3.8: </span>Added context manager support.</p>413</div>414<dl class="py method">415<dt class="sig sig-object py" id="profiling.tracing.Profile.enable">416<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="#profiling.tracing.Profile.enable" title="Link to this definition">¶</a></dt>417<dd><p>Start collecting profiling data.</p>418</dd></dl>419 420<dl class="py method">421<dt class="sig sig-object py" id="profiling.tracing.Profile.disable">422<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="#profiling.tracing.Profile.disable" title="Link to this definition">¶</a></dt>423<dd><p>Stop collecting profiling data.</p>424</dd></dl>425 426<dl class="py method">427<dt class="sig sig-object py" id="profiling.tracing.Profile.create_stats">428<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="#profiling.tracing.Profile.create_stats" title="Link to this definition">¶</a></dt>429<dd><p>Stop collecting data and record the results internally as the current430profile.</p>431</dd></dl>432 433<dl class="py method">434<dt class="sig sig-object py" id="profiling.tracing.Profile.print_stats">435<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="#profiling.tracing.Profile.print_stats" title="Link to this definition">¶</a></dt>436<dd><p>Create a <a class="reference internal" href="pstats.html#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">pstats.Stats</span></code></a> object from the current profile and print437the results to standard output.</p>438<p>The <em>sort</em> argument specifies the sorting order. It accepts a single439key or a tuple of keys for multi-level sorting, using the same values440as <a class="reference internal" href="pstats.html#pstats.Stats.sort_stats" title="pstats.Stats.sort_stats"><code class="xref py py-meth docutils literal notranslate"><span class="pre">pstats.Stats.sort_stats()</span></code></a>.</p>441<div class="versionadded">442<p><span class="versionmodified added">Added in version 3.13: </span>Support for a tuple of sort keys.</p>443</div>444</dd></dl>445 446<dl class="py method">447<dt class="sig sig-object py" id="profiling.tracing.Profile.dump_stats">448<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="#profiling.tracing.Profile.dump_stats" title="Link to this definition">¶</a></dt>449<dd><p>Write the current profile data to <em>filename</em>. The file can be read by450<a class="reference internal" href="pstats.html#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">pstats.Stats</span></code></a> for later analysis.</p>451</dd></dl>452 453<dl class="py method">454<dt class="sig sig-object py" id="profiling.tracing.Profile.run">455<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="#profiling.tracing.Profile.run" title="Link to this definition">¶</a></dt>456<dd><p>Profile the command string 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>457</dd></dl>458 459<dl class="py method">460<dt class="sig sig-object py" id="profiling.tracing.Profile.runctx">461<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="#profiling.tracing.Profile.runctx" title="Link to this definition">¶</a></dt>462<dd><p>Profile the command string 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 specified463namespaces.</p>464</dd></dl>465 466<dl class="py method">467<dt class="sig sig-object py" id="profiling.tracing.Profile.runcall">468<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="positional-only-separator o"><abbr title="Positional-only parameter separator (PEP 570)"><span class="pre">/</span></abbr></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="#profiling.tracing.Profile.runcall" title="Link to this definition">¶</a></dt>469<dd><p>Profile a function call. Returns whatever <em>func</em> returns:</p>470<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">result</span> <span class="o">=</span> <span class="n">pr</span><span class="o">.</span><span class="n">runcall</span><span class="p">(</span><span class="n">my_function</span><span class="p">,</span> <span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">,</span> <span class="n">keyword</span><span class="o">=</span><span class="n">value</span><span class="p">)</span>471</pre></div>472</div>473</dd></dl>474 475</dd></dl>476 477<div class="admonition note">478<p class="admonition-title">Note</p>479<p>Profiling requires that the profiled code returns normally. If the480interpreter terminates (for example, via <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>) during481profiling, no results will be available.</p>482</div>483</section>484<section id="using-a-custom-timer">485<h2>Using a custom timer<a class="headerlink" href="#using-a-custom-timer" title="Link to this heading">¶</a></h2>486<p>The <a class="reference internal" href="#profiling.tracing.Profile" title="profiling.tracing.Profile"><code class="xref py py-class docutils literal notranslate"><span class="pre">Profile</span></code></a> class accepts a custom timing function, allowing you to487measure different aspects of execution such as wall-clock time or CPU time.488Pass the timing function to the constructor:</p>489<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">pr</span> <span class="o">=</span> <span class="n">profiling</span><span class="o">.</span><span class="n">tracing</span><span class="o">.</span><span class="n">Profile</span><span class="p">(</span><span class="n">my_timer_function</span><span class="p">)</span>490</pre></div>491</div>492<p>The timer function must return a single number representing the current time.493If it returns integers, also specify <em>timeunit</em> to indicate the duration of494one unit:</p>495<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Timer returns time in milliseconds</span>496<span class="n">pr</span> <span class="o">=</span> <span class="n">profiling</span><span class="o">.</span><span class="n">tracing</span><span class="o">.</span><span class="n">Profile</span><span class="p">(</span><span class="n">my_ms_timer</span><span class="p">,</span> <span class="mf">0.001</span><span class="p">)</span>497</pre></div>498</div>499<p>For best performance, the timer function should be as fast as possible. The500profiler calls it frequently, so timer overhead directly affects profiling501overhead.</p>502<p>The <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> module provides several functions suitable for use as custom503timers:</p>504<ul class="simple">505<li><p><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> for high-resolution wall-clock time</p></li>506<li><p><a class="reference internal" href="time.html#time.process_time" title="time.process_time"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.process_time()</span></code></a> for CPU time (excluding sleep)</p></li>507<li><p><a class="reference internal" href="time.html#time.monotonic" title="time.monotonic"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.monotonic()</span></code></a> for monotonic clock time</p></li>508</ul>509</section>510<section id="limitations">511<h2>Limitations<a class="headerlink" href="#limitations" title="Link to this heading">¶</a></h2>512<p>Deterministic profiling has inherent limitations related to timing accuracy.</p>513<p>The underlying timer typically has a resolution of about one millisecond.514Measurements cannot be more accurate than this resolution. With enough515measurements, timing errors tend to average out, but individual measurements516may be imprecise.</p>517<p>There is also latency between when an event occurs and when the profiler518captures the timestamp. Similarly, there is latency after reading the519timestamp before user code resumes. Functions called frequently accumulate520this latency, which can make them appear slower than they actually are. This521error is typically less than one clock tick per call but can become522significant for functions called many times.</p>523<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">profiling.tracing</span></code> module (and its <code class="docutils literal notranslate"><span class="pre">cProfile</span></code> alias) is524implemented as a C extension with low overhead, so these timing issues are525less pronounced than with the deprecated pure Python <a class="reference internal" href="profile.html#module-profile" title="profile: Pure Python profiler (deprecated). (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> module.</p>526<div class="admonition seealso">527<p class="admonition-title">See also</p>528<dl class="simple">529<dt><a class="reference internal" href="profiling.html#module-profiling" title="profiling: Python profiling tools for performance analysis."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profiling</span></code></a></dt><dd><p>Overview of Python profiling tools and guidance on choosing a profiler.</p>530</dd>531<dt><a class="reference internal" href="profiling.sampling.html#module-profiling.sampling" title="profiling.sampling: Statistical sampling profiler for Python processes."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profiling.sampling</span></code></a></dt><dd><p>Statistical sampling profiler for production use.</p>532</dd>533<dt><a class="reference internal" href="pstats.html#module-pstats" title="pstats: Statistics object for analyzing profiler output."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pstats</span></code></a></dt><dd><p>Statistics analysis and formatting for profile data.</p>534</dd>535<dt><a class="reference internal" href="profile.html#module-profile" title="profile: Pure Python profiler (deprecated). (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a></dt><dd><p>Deprecated pure Python profiler (includes calibration documentation).</p>536</dd>537</dl>538</div>539</section>540</section>541 542 543            <div class="clearer"></div>544          </div>545        </div>546      </div>547      <div class="sphinxsidebar" role="navigation" aria-label="Main">548        <div class="sphinxsidebarwrapper">549  <div>550    <h3><a href="../contents.html">Table of Contents</a></h3>551    <ul>552<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">profiling.tracing</span></code> — Deterministic profiler</a><ul>553<li><a class="reference internal" href="#what-is-deterministic-profiling">What is deterministic profiling?</a></li>554<li><a class="reference internal" href="#command-line-interface">Command-line interface</a></li>555<li><a class="reference internal" href="#programmatic-usage-examples">Programmatic usage examples</a><ul>556<li><a class="reference internal" href="#basic-profiling">Basic profiling</a></li>557<li><a class="reference internal" href="#using-the-profile-class">Using the <code class="xref py py-class docutils literal notranslate"><span class="pre">Profile</span></code> class</a></li>558</ul>559</li>560<li><a class="reference internal" href="#module-reference">Module reference</a></li>561<li><a class="reference internal" href="#using-a-custom-timer">Using a custom timer</a></li>562<li><a class="reference internal" href="#limitations">Limitations</a></li>563</ul>564</li>565</ul>566 567  </div>568  <div>569    <h4>Previous topic</h4>570    <p class="topless"><a href="profiling.html"571                          title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">profiling</span></code> — Python profilers</a></p>572  </div>573  <div>574    <h4>Next topic</h4>575    <p class="topless"><a href="profiling.sampling.html"576                          title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">profiling.sampling</span></code> — Statistical profiler</a></p>577  </div>578  <script>579    document.addEventListener('DOMContentLoaded', () => {580        const title = document.querySelector('meta[property="og:title"]').content;581        const elements = document.querySelectorAll('.improvepage');582        const pageurl = window.location.href.split('?')[0];583        elements.forEach(element => {584            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));585            url.searchParams.set('pagetitle', title);586            url.searchParams.set('pageurl', pageurl);587            url.searchParams.set('pagesource', "library/profiling.tracing.rst");588            element.href = url.toString();589        });590    });591  </script>592  <div role="note" aria-label="source link">593    <h3>This page</h3>594    <ul class="this-page-menu">595      <li><a href="../bugs.html">Report a bug</a></li>596      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>597      <li>598        <a href="https://github.com/python/cpython/blob/main/Doc/library/profiling.tracing.rst?plain=1"599            rel="nofollow">Show source600        </a>601      </li>602      603    </ul>604  </div>605        </div>606<div id="sidebarbutton" title="Collapse sidebar">607<span>«</span>608</div>609 610      </div>611      <div class="clearer"></div>612    </div>  613    <div class="related" role="navigation" aria-label="Related">614      <h3>Navigation</h3>615      <ul>616        <li class="right" style="margin-right: 10px">617          <a href="../genindex.html" title="General Index"618             >index</a></li>619        <li class="right" >620          <a href="../py-modindex.html" title="Python Module Index"621             >modules</a> |</li>622        <li class="right" >623          <a href="profiling.sampling.html" title="profiling.sampling — Statistical profiler"624             >next</a> |</li>625        <li class="right" >626          <a href="profiling.html" title="profiling — Python profilers"627             >previous</a> |</li>628 629          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>630          <li><a href="https://www.python.org/">Python</a> &#187;</li>631          <li class="switchers">632            <div class="language_switcher_placeholder"></div>633            <div class="version_switcher_placeholder"></div>634          </li>635          <li>636              637          </li>638    <li id="cpython-language-and-version">639      <a href="../index.html">3.15.0a6 Documentation</a> &#187;640    </li>641 642          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>643          <li class="nav-item nav-item-2"><a href="debug.html" >Debugging and profiling</a> &#187;</li>644          <li class="nav-item nav-item-3"><a href="profiling.html" ><code class="xref py py-mod docutils literal notranslate"><span class="pre">profiling</span></code> — Python profilers</a> &#187;</li>645        <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">profiling.tracing</span></code> — Deterministic profiler</a></li>646                <li class="right">647                    648 649    <div class="inline-search" role="search">650        <form class="inline-search" action="../search.html" method="get">651          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">652          <input type="submit" value="Go">653        </form>654    </div>655                     |656                </li>657            <li class="right">658<label class="theme-selector-label">659    Theme660    <select class="theme-selector" oninput="activateTheme(this.value)">661        <option value="auto" selected>Auto</option>662        <option value="light">Light</option>663        <option value="dark">Dark</option>664    </select>665</label> |</li>666            667      </ul>668    </div>  669    <div class="footer">670    &copy; <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation.671    <br>672    This page is licensed under the Python Software Foundation License Version 2.673    <br>674    Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.675    <br>676    677      See <a href="/license.html">History and License</a> for more information.<br>678    679    680    <br>681 682    The Python Software Foundation is a non-profit corporation.683<a href="https://www.python.org/psf/donations/">Please donate.</a>684<br>685    <br>686      Last updated on Mar 10, 2026 (08:58 UTC).687    688      <a href="/bugs.html">Found a bug</a>?689    690    <br>691 692    Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.693    </div>694 695  </body>696</html>