DEV Community

Alex Chen
Alex Chen

Posted on

Quick Tip: Find What's Actually Slow in Your Python Script with cProfile in 10 Seconds

Quick Tip

Stop guessing which function is slow. Python ships with a profiler:

python -m cProfile -s cumtime my_script.py | head -20
Enter fullscreen mode Exit fullscreen mode

Output ranks every function by cumulative time — the total time spent inside it including everything it called:

   ncalls  tottime  cumtime  filename:lineno(function)
        1    0.000    4.812  my_script.py:3(main)
      500    3.901    3.901  my_script.py:17(parse_row)
        1    0.210    0.911  my_script.py:40(load_csv)
Enter fullscreen mode Exit fullscreen mode

Three sort keys worth memorizing:

Flag Sorts by Use when
-s cumtime Cumulative time Finding the slow path (default choice)
-s tottime Self time only Finding the slow function body
-s calls Call count Finding accidental O(n²) loops

Last week this took a script I was about to rewrite in Rust from 4.8s to 0.6s — the "hot loop" was actually parse_row being called 500 times on data I could have parsed once with csv.DictReader. No rewrite needed.

Save the output for later diffing:

python -m cProfile -o before.prof my_script.py
python -c "import pstats; pstats.Stats('before.prof').sort_stats('cumtime').print_stats(15)"
Enter fullscreen mode Exit fullscreen mode

Zero dependencies, zero code changes, works on any Python 3.x.

Powered by MonkeyCode — free AI coding assistant: https://ly.cyberserval.tech/iIETXiF

python #coding #tips #productivity

Top comments (0)