Stop 14 · Advanced PythonTopics · 7/8

Profiling with cProfile

Part of the Python Roadmap

In short

Programmers are famously bad at guessing which part of their code is slow. A profiler measures it, so you spend ten minutes fixing the real problem instead of a day polishing the wrong function.

Profiling measures where your program actually spends time, so you optimise the right part. cProfile records time per function, and timeit compares small snippets accurately.

The jaadu, dressed as a doctor with a stethoscope, listens carefully to a small whirring machine on an examination table and peers at a long paper report.

Think of it like this

Tests before treatment

A good doctor doesn't prescribe medicine because you look tired. They order blood tests, read the report and treat what the numbers show. cProfile is the blood test for your program: a report of every function, how many times it ran and how long it took.

Watch it happen

Reading the profile, sorted by time

main
0
find_repeat_customers
1
make_orders
2
randint
3

1/5cProfile lists every function that ran. Sort by cumulative time to see where the time goes.

The big ideas

What you need to know

Measure first

Run the profiler on a realistic input before changing anything, and again after, to prove the fix worked.

tottime vs cumtime

tottime is time inside the function itself. cumtime includes everything it called. Start from the biggest cumtime.

timeit for small snippets

python -m timeit compares two short pieces of code by running them many times and reporting the best timings.

Usual fixes

Better data structures (set or dict lookups), avoiding repeated work, caching with functools.cache, or moving heavy maths to NumPy.

See it in code

Walk through the code

python
1import cProfile2import pstats3import random4 5def make_orders(n: int) -> list[dict]:6    return [{"customer_id": random.randint(1, n), "amount": 499} for _ in range(n)]7 8def find_repeat_customers(orders: list[dict]) -> list[int]:9    seen = []                      # slow: list lookups scan every item10    repeats = []11    for order in orders:12        cid = order["customer_id"]13        if cid in seen:14            repeats.append(cid)15        else:16            seen.append(cid)17    return repeats18 19def main() -> None:20    orders = make_orders(20_000)21    repeats = find_repeat_customers(orders)22    print(len(repeats), "repeat orders")23 24with cProfile.Profile() as profiler:25    main()26 27stats = pstats.Stats(profiler)28stats.sort_stats("cumulative").print_stats(5)

1/4The hidden problem: in on a list checks items one by one, so the loop becomes O(n²).

Profile a function, then fix it by changing seen = [] to seen = set() and seen.append to seen.add. Profile again to see the difference.

Save yourself the pain

Common mistakes

Oops

Optimising code because it looks slow.

Do this instead

Profile first. The real bottleneck is often a lookup or a repeated database call somewhere you didn't expect.

Oops

Timing code once with time.time() on a tiny input.

Do this instead

Use realistic input sizes and time.perf_counter or timeit, which repeat runs to smooth out noise.

Oops

Reading only tottime and missing the function that calls the slow code.

Do this instead

Sort by cumulative time to see which high-level step is expensive, then drill down.

Your mission

Find and fix a bottleneck

~25 min

Quick check

In a cProfile report, what does cumtime include that tottime does not?

Go deeper

  1. 1Run python -m cProfile -s cumtime on a slow script.
  2. 2Use timeit to compare a loop with a list comprehension.
  3. 3Optimise only the top few functions the profile shows.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge