Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 13.7 — Measuring Speed: timeit and cProfile
Python · Example 2 of 2

cProfile call counts and tracemalloc

Never guess where a program is slow. Time small snippets with timeit, find the slow function with cProfile, find the memory hog with tracemalloc, and always compare before and after.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Read time.perf_counter() before and after sum(range(100_000)), subtract to get the elapsed time, and print elapsed is not negative: True by checking elapsed >= 0. Do not print the elapsed time itself.

02

Profile a function work() that calls helper(i) fifty times, and print the call counts of both from pstats.

03

Use tracemalloc to check that building list(range(500_000)) grows traced memory by more than a megabyte.

Explain it without notes

01

Why measure before optimising, and what is a good workflow?

02

What do ncalls, tottime and cumtime mean in a cProfile table?

03

Why take the minimum of several timeit repeats?

04

When would you choose py-spy over cProfile?

cProfile call counts and tracemalloc
Sign in to run this example in your browser.

Expected output

fib        called 3177 times
load       called 1 times
main       called 1 times
the big list added over 1 MB: True
peak is at least current: True