cProfile/profiling.tracing¶
Usually, a profile is created in the command line with cProfile or, from
Python 3.15 onwards, with profiling.tracing, which then displays its
profile statistics. However, this can quickly become very tedious, especially
when reading extensive profiles or sorting the data. A more flexible approach is
to save the profile data in a file instead, which can then be read with the
pstats module:
uv run python -m cProfile -o PROFILE (SCRIPT | -m {MODULE)runs cProfile to profile your script or module and saves the results in a file specified by the-ooption.uv run python -m (cProfile | profiling.tracing) -o profile (SCRIPT | -m MODULE) <<< $'sort cumtimenstats 100' | lesspasses the following two commands to thepstatsmodule using the$syntax.sort cumtimesorts the output by cumulative time, starting with the largest.
To sort by other metrics, simply replace
cumtimewith a value frompstats.Stats.sort_stats().stats 100displays the first 100 lines of the profile.
The output is passed to
lessso you can view the results. Press q to exit when you are finished.Before and after optimisation can be easily compared, for example with:
$ uv run python -m cProfile -o before.profile main.py $ git switch -c main_optimisation ... $ uv run python -m cProfile -o after.profile main.py