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.
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.
Profile a function work() that calls helper(i) fifty times, and print the call counts of both from pstats.
Use tracemalloc to check that building list(range(500_000)) grows traced memory by more than a megabyte.
Explain it without notes
Why measure before optimising, and what is a good workflow?
What do ncalls, tottime and cumtime mean in a cProfile table?
Why take the minimum of several timeit repeats?
When would you choose py-spy over cProfile?
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