Command Palette

Search for a command to run...

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

Count the work instead of timing it

The timeit part prints counts and types only, never the seconds, so this output is the same on every run.

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?

Count the work instead of timing it
Sign in to run this example in your browser.

Expected output

list  comparisons: 1000
set   comparisons: 1
calls made: 300
repeat returns 3 numbers (seconds, vary every run)
each is a float: True
trust the smallest of the repeats: True