Sub topic 1
Why You Measure Before You Optimize
Prerequisites
You should be able to write and run Python functions, loops, and modules. You should also know basic lists, dictionaries, and sets, and be comfortable running scripts from a terminal.
Measure Before You Optimize
Optimization means changing code to reduce its runtime or memory use. Start with a measurable target, such as “this function must finish in under 100 milliseconds.” Without a target and a baseline, a change may make code harder to read without making it faster.
Measure realistic input sizes. A small test can hide a slow algorithm.
Timing Snippets with `perf_counter` and `timeit`
time.perf_counter() measures elapsed wall-clock time with a high-resolution timer. Use it around a meaningful operation, and repeat the operation when one run is too short to measure reliably.
from time import perf_counter
values = list(range(1_000_000))
start = perf_counter()
total = sum(values)
elapsed = perf_counter() - start
print(total, f"{elapsed:.6f} seconds")For small comparisons, timeit repeats code and reduces noise from a single run.
import timeit
items_list = list(range(10_000))
items_set = set(items_list)
list_time = timeit.timeit("9_999 in items_list", globals=globals(), number=1_000)
set_time = timeit.timeit("9_999 in items_set", globals=globals(), number=1_000)
print(list_time, set_time)A set usually provides faster membership tests than a list because it uses hashing rather than checking items one by one.
Profiling a Whole Program with `cProfile`
Timing tells you how long something takes. A profiler shows where a program spends that time. Run a script with:
python -m cProfile -s cumulative myscript.pyThe -s cumulative option sorts functions by the total time spent in each function and the functions it calls.
Reading Profile Results
cProfile reports several useful values:
| Field | Meaning |
|---|---|
| `tottime` | Time spent inside the function itself |
| `cumtime` | Time spent in the function and its callees |
| `ncalls` | Number of calls |
A high tottime points to work directly inside a function. A high cumtime may identify a wrapper that calls the real hot spot. Inspect callers and callees before changing code, then measure again.
Exercise
Which tool should you use first to compare two short expressions, and which profile field includes called functions?
Show answer
Use timeit for the comparison. cumulative time includes the function and its callees.