Skip to main content
  1. Posts/

Think Your Python Code Is Slow? Stop Guessing and Start Measuring

🐢 Your Python code is slow. But where exactly?

Optimizing without data is just guessing. Donald Knuth said it well: “Premature optimization is the root of all evil.” Before touching a single line of code, you need to know which function is actually consuming the time.

Thomas Reid walks through the exact workflow using two tools:

🔍 cProfile — ships with Python, no install needed:

import cProfile, pstats, io

pr = cProfile.Profile()
pr.enable()
run_all_systems()  # your function to profile
pr.disable()

s = io.StringIO()
pstats.Stats(pr, stream=s).sort_stats("cumtime").print_stats(10)
print(s.getvalue())

📊 snakeviz — turns that output into an interactive visual map:

pip install snakeviz
%load_ext snakeviz
%%snakeviz
run_all_systems()

The result: in a 30-second script, the real bottleneck was massive iteration (171M calls to an empty function), not the CPU-heavy task. Without profiling, you’d have optimized the wrong thing.

Quick explanation
#

Profiling is like a doctor running tests before surgery. cProfile records how many times each function is called and how long it takes. snakeviz turns that table of numbers into an interactive icicle chart where you can visually see which part of your code is the actual problem.

More information at the link 👇

Also published on LinkedIn.
Juan Pedro Bretti Mandarano
Author
Juan Pedro Bretti Mandarano