brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python -m cProfile -s cumtime shows where a script spends its time

Python
~/tips/tip-python-cprofile-sort-cumtime

python3 -m cProfile -s cumtime script.py | head -20

Profiles a whole script with the standard library and sorts functions by time spent.

Before I optimise anything I want a profile, and the standard library already has one.

python3 -m cProfile -s cumtime script.py | head -20
python3 -m cProfile -o out.prof script.py

-s cumtime sorts by cumulative time, which puts the top-level call chains first, and head trims the report. The script’s own output goes through the same pipe, so redirect it if it gets in the way. -o out.prof saves the raw data so you can inspect it later with python3 -m pstats out.prof. The profiler adds overhead, so use the proportions and not the absolute seconds. For one small expression, timeit is the better tool.

Further reading: profile and cProfile documentation

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link