Text of docs.python.org › pa › 3 › library › profile.html as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

profile --- Pure Python profiler — Python 3.15.2 documentation

Navigation index modules | next | previous | Python » 3.15.2 documentation » The Python standard library » Superseded modules » profile --- Pure Python profiler | Theme | profile --- Pure Python profiler ¶ Source code: Lib/profile.py Deprecated since version 3.15, will be removed in version 3.17. The profile module is deprecated and will be removed in Python 3.17. Use profiling.tracing instead. The profile module provides a pure Python implementation of a deterministic profiler.

While useful for understanding profiler internals or extending profiler behavior through subclassing, its pure Python implementation introduces significant overhead compared to the C-based profiling.tracing module. For most profiling tasks, use: profiling.sampling for production debugging with zero overhead profiling.tracing for development and testing Migration ¶ Migrating from profile to profiling.tracing is straightforward.

The APIs are compatible: # Old (deprecated) import profile profile . run ( 'my_function()' ) # New (recommended) import profiling.tracing profiling . tracing . run ( 'my_function()' ) For most code, replacing import profile with import profiling.tracing (and using profiling.tracing instead of profile throughout) provides a straightforward migration path. Note The cProfile module remains available as a backward-compatible alias to profiling.tracing .

Existing code using import cProfile will continue to work without modification. profile and profiling.tracing module reference ¶ Both the profile and profiling.tracing modules provide the following functions: profile. run ( command , filename = None , sort = -1 ) ¶ This function takes a single argument that can be passed to the exec() function, and an optional file name. In all cases this routine executes: exec ( command , __main__ . __dict__ , __main__ . __dict__ ) and gathers profiling statistics from the execution.

If no file name is present, then this function automatically creates a Stats instance and prints a simple profiling report. If the sort value is specified, it is passed to this Stats instance to control how the results are sorted. profile. runctx ( command , globals , locals , filename = None , sort = -1 ) ¶ This function is similar to run() , with added arguments to supply the globals and locals mappings for the command string.

This routine executes: exec ( command , globals , locals ) and gathers profiling statistics as in the run() function above. class profile. Profile ( timer = None , timeunit = 0.0 , subcalls = True , builtins = True ) ¶ This class is normally only used if more precise control over profiling is needed than what the profiling.tracing.run() function provides. A custom timer can be supplied for measuring how long code takes to run via the timer argument.

This must be a function that returns a single number representing the current time. If the number is an integer, the timeunit specifies a multiplier that specifies the duration of each unit of time. For example, if the timer returns times measured in thousandths of seconds, the time unit would be .001 . Directly using the Profile class allows formatting profile results without writing the profile data to a file: import profiling.tracing import pstats import io from pstats import SortKey pr = profiling . tracing .

Profile () pr . enable () # ... do something ... pr . disable () s = io . StringIO () sortby = SortKey . CUMULATIVE ps = pstats . Stats ( pr , stream = s ) . sort_stats ( sortby ) ps . print_stats () print ( s . getvalue ()) The Profile class can also be used as a context manager (supported only in profiling.tracing , not in the deprecated profile module; see Context Manager Types ): import profiling.tracing with profiling . tracing .

Profile () as pr : # ... do something ... pr . print_stats () Changed in version 3.8: Added context manager support. enable ( ) ¶ Start collecting profiling data. Only in profiling.tracing . disable ( ) ¶ Stop collecting profiling data. Only in profiling.tracing . create_stats ( ) ¶ Stop collecting profiling data and record the results internally as the current profile. print_stats ( sort = -1 ) ¶ Create a Stats object based on the current profile and print the results to stdout.

The sort parameter specifies the sorting order of the displayed statistics. It accepts a single key or a tuple of keys to enable multi-level sorting, as in pstats.Stats.sort_stats() . Added in version 3.13: print_stats() now accepts a tuple of keys. dump_stats ( filename ) ¶ Write the results of the current profile to filename . run ( cmd ) ¶ Profile the cmd via exec() . runctx ( cmd , globals , locals ) ¶ Profile the cmd via exec() with the specified global and local environment. runcall ( func , / , * args , ** kwargs ) ¶ Profile func(*args, **kwargs) Note that profiling will only work if the called command/function actually returns.

If the interpreter is terminated (e.g. via a sys.exit() call during the called command/function execution) no profiling results will be printed. Differences from profiling.tracing ¶ The profile module differs from profiling.tracing in several ways: Higher overhead. The pure Python implementation is significantly slower than the C implementation, making it unsuitable for profiling long-running programs or performance-sensitive code.

Calibration support. The profile module supports calibration to compensate for profiling overhead. This is not needed in profiling.tracing because the C implementation has negligible overhead. Custom timers. Both modules support custom timers, but profile accepts timer functions that return tuples (like os.times() ), while profiling.tracing requires a function returning a single number. Subclassing. The pure Python implementation is easier to subclass and extend for custom profiling behavior.

What is deterministic profiling? ¶ Deterministic profiling is meant to reflect the fact that all function call , function return , and exception events are monitored, and precise timings are made for the intervals between these events (during which time the user's code is executing). In contrast, statistical profiling (which is provided by the profiling.sampling module) periodically samples the effective instruction pointer, and deduces where time is being spent.

The latter technique traditionally involves less overhead (as the code does not need to be instrumented), but provides only relative indications of where time is being spent. In Python, since there is an interpreter active during execution, the presence of instrumented code is not required in order to do deterministic profiling. Python automatically provides a hook (optional callback) for each event. In addition, the interpreted nature of Python tends to add so much overhead to execution, that deterministic profiling tends to only add small processing overhead in typical applications.

The result is that deterministic profiling is not that expensive, yet provides extensive run time statistics about the execution of a Python program. Call count statistics can be used to identify bugs in code (surprising counts), and to identify possible inline-expansion points (high call counts). Internal time statistics can be used to identify "hot loops" that should be carefully optimized. Cumulative time statistics should be used to identify high level errors in the selection of algorithms.

Note that the unusual handling of cumulative times in this profiler allows statistics for recursive implementations of algorithms to be directly compared to iterative implementations. Limitations ¶ One limitation has to do with accuracy of timing information. There is a fundamental problem with deterministic profilers involving accuracy. The most obvious restriction is that the underlying "clock" is only ticking at a rate (typically) of about .001 seconds.

Hence no measurements will be more accurate than the underlying clock. If enough measurements are taken, then the "error" will tend to average out. Unfortuna

The rest of this page is on the live site.