Part 14 / Topic 9 of 11
Performance measurement
Profiling means measuring where a program spends its time. People are bad at guessing this: the slow part is often not where you think. The golden rule is measure, don't guess: measure, change one thing, measure again. Think of a doctor: they run tests before they operate.
| Tool | Use it for |
|---|---|
timeit |
comparing two small snippets fairly |
time.perf_counter() |
timing one block of your program |
cProfile + pstats |
finding which function is slow in a whole program |
timeit
timeit runs a snippet many times and reports the total, so tiny differences become visible. From the terminal (CLI, command-line interface), -s is setup code that runs once:
$ python -m timeit -s "ids = list(range(10_000))" "9_999 in ids"
5000 loops, best of 5: 56.1 usec per loop (varies)
$ python -m timeit -s "ids = set(range(10_000))" "9_999 in ids"
10000000 loops, best of 5: 21.6 nsec per loop (varies)
(usec = microseconds, millionths of a second; nsec = nanoseconds, billionths.)
From code, timeit.timeit(stmt, setup=..., number=N) returns the total seconds for N runs:
import timeit
setup = "ids = list(range(10_000)); id_set = set(ids)"
list_time = timeit.timeit("9_999 in ids", setup=setup, number=1_000)
set_time = timeit.timeit("9_999 in id_set", setup=setup, number=1_000)
print(f"list: {list_time:.4f} s, set: {set_time:.6f} s")
# list: 0.0571 s, set: 0.000022 s (varies)
print(set_time < list_time) # True
You can also pass a function: timeit.timeit(lambda: build_report(orders), number=5).
time.perf_counter
time.perf_counter() is a high-precision clock for measuring short durations. Use it, not time.time(), for timing.
import time
start = time.perf_counter()
total = sum(n * n for n in range(1_000_000))
took = time.perf_counter() - start
print(f"took {took * 1000:.1f} ms") # took 52.3 ms (varies)
cProfile + pstats
cProfile records every function call and how long it took. Run a whole script from the terminal, sorted by cumulative time:
$ python -m cProfile -s cumulative sales_report.py
Or in code, and read the result with pstats:
import cProfile
import pstats
def clean(names):
return [n.strip().title() for n in names]
def find_repeats(names):
return sorted({n for n in names if names.count(n) > 1}) # slow
def job():
names = clean([" asha", "ravi ", "Asha", "meera"] * 1_000)
return find_repeats(names)
profiler = cProfile.Profile()
profiler.enable()
job()
profiler.disable()
pstats.Stats(profiler).strip_dirs().sort_stats("cumulative").print_stats(5)
Output (shortened, varies):
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.061 0.061 block.py:10(job)
1 0.001 0.001 0.059 0.059 block.py:7(find_repeats)
4000 0.058 0.000 0.058 0.000 {method 'count' of 'list' objects}
1 0.001 0.001 0.002 0.002 block.py:4(clean)
Reading a profile
| Column | Meaning |
|---|---|
ncalls |
how many times the function was called |
tottime |
time spent inside the function itself, not counting functions it called |
cumtime |
cumulative time: the function plus everything it called |
percall |
the time before it divided by ncalls |
filename:lineno(function) |
where the function is; {...} means a built-in |
How to read it:
- Sort by
cumtimeand go down the list to the first function you wrote with a bigcumtime: herefind_repeats. - Look at its children: a built-in with a huge
tottime(list.count, called 4,000 times) is the real cost. - A big
ncallsfor something cheap means "doing the same work again and again".
๐ Going deeper: profiling makes code slower, so trust the profile for where time goes, and
timeit/perf_counterfor how much.stats.sort_stats("tottime")lists the functions that are busy themselves.
Done here? The practice set for Part 14 โ 8 exercises with solutions โ is on the part page.