Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

cProfile.run

Profiles trusted statement text in the main module namespace and optionally writes the collected statistics to a file.

Version: Python 3.14; repository image, production runtime not attested

Syntax

cProfile.run(statement, filename=None, sort=-1)

Profiles trusted statement text in the main module namespace and optionally writes the collected statistics to a file.

Use a temporary file and inspect call counts rather than comparing timing values, which vary between runs.

The command executes with the main module dictionary for both globals and locals. With filename=None the profiler prints a report ordered by sort. With a filename it writes a stats dump for pstats.Stats. run returns None. One invocation of square registers one total call. In CPython 3.14.9, run suppresses SystemExit from the command and returns None. ValueError propagates. With filename supplied, pstats.Stats can read the data after either exception.

import cProfile, pstats, tempfile, os, __main__
def probe(): return 5
__main__.__dict__['profile_probe']=probe
try:
    with tempfile.TemporaryDirectory() as directory:
        target=os.path.join(directory,'p.prof')
        assert cProfile.run("profile_probe()", target) is None
        assert [v[1] for k,v in pstats.Stats(target).stats.items() if k[2]=='probe']==[1]
finally: del __main__.__dict__['profile_probe']
with tempfile.TemporaryDirectory() as directory:
    for exc in ('SystemExit','ValueError'):
        path=os.path.join(directory,exc+'.prof')
        try: result=cProfile.run("raise "+exc+"()",path)
        except ValueError: assert exc=='ValueError'
        else: assert exc=='SystemExit' and result is None
        assert pstats.Stats(path).total_calls>0

Examples

import cProfile
import pstats
from pathlib import Path
from tempfile import TemporaryDirectory

def square(n): return n * n

with TemporaryDirectory() as d:
    p = str(Path(d) / "sample.prof")
    cProfile.run("square(4)", p)
    print(sum(stat[1] for key, stat in pstats.Stats(p).stats.items() if key[2] == "square"))

Result

1

The command executes with the main module dictionary for both globals and locals. With filename=None the profiler prints a report ordered by sort. With a filename it writes a stats dump for pstats.Stats. run returns None. One invocation of square registers one total call. In CPython 3.14.9, run suppresses SystemExit from the command and returns None. ValueError propagates. With filename supplied, pstats.Stats can read the data after either exception.

Sources