Sub topic 2
Timing snippets with perf_counter and timeit
This chapter assumes you can write Python functions and loops, run scripts from a terminal, and use lists and sets. You do not need any profiling experience. By the end you will be able to time a block of code, time a small snippet repeatedly, and avoid the mistakes that make benchmark numbers misleading.
Why the choice of clock matters
Python has several ways to read a clock. They measure different things, and only one of them is right for timing code.
| Function | What it measures | Use it for timing? |
|---|---|---|
| `time.time()` | Wall-clock time since the Unix epoch. It can jump when the system clock is adjusted. | No |
| `time.perf_counter()` | A monotonic clock with the highest available resolution. It never goes backward. | Yes, for elapsed time |
| `time.process_time()` | CPU time used by the current process. It excludes sleeping and waiting. | Yes, when you want CPU cost only |
| `time.perf_counter_ns()` | The same clock as `perf_counter`, returned as an integer number of nanoseconds. | Yes, to avoid float rounding |
The value returned by perf_counter() has no meaning on its own. Only the difference between two calls is meaningful.
The distinction between wall time and CPU time shows up whenever your code waits. A function that calls time.sleep(1) takes one second by perf_counter and almost zero by process_time. Which one you want depends on your question. "How long does the user wait?" needs perf_counter. "How much computing does this cost?" needs process_time.
Timing a block with perf_counter
The basic pattern is to read the clock, run the code, read the clock again, and subtract.
import time
start = time.perf_counter()
total = sum(i * i for i in range(1_000_000))
elapsed = time.perf_counter() - start
print(f"sum of squares: {elapsed:.4f}s")If you time many blocks, wrap the pattern in a context manager so you do not repeat it. The finally clause makes sure the time is reported even when the block raises an exception.
import time
from contextlib import contextmanager
@contextmanager
def timer(label):
start = time.perf_counter()
try:
yield
finally:
elapsed = time.perf_counter() - start
print(f"{label}: {elapsed:.4f}s")
with timer("build list"):
data = [i * 2 for i in range(1_000_000)]
with timer("sort list"):
data.sort(reverse=True)This is a good tool for coarse questions, such as "which stage of my pipeline takes seconds?" It is a poor tool for fine questions, such as "is version A faster than version B by 5%?" The next section explains why.
Why one measurement is not enough
A single timing includes noise from sources outside your code:
- Other processes compete for the CPU.
- The CPU changes its clock speed as it heats up or saves power.
- The first run pays one-time costs, such as filling CPU caches, importing modules, and allocating memory.
- Python's garbage collector may run in the middle of one measurement and not another.
Run the same snippet five times and you will often see five different numbers. The noise only ever adds time. It never makes your code run faster than it can. So the fastest of several runs is the best estimate of what the code costs, and the mean is pulled upward by interference. This is the reasoning behind the timeit module's documentation advice to take the minimum.
For very short snippets there is a second problem. A snippet that takes a microsecond is close to the resolution of the clock and to the overhead of the two clock calls. You need to run it thousands of times and divide. Doing this by hand is tedious, so the standard library does it for you.
Repeated timing with timeit
timeit.timeit(stmt, ...) runs a statement number times and returns the total elapsed seconds. It uses perf_counter internally and disables garbage collection during the run by default, which removes one source of noise.
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(f"list membership: {list_time:.4f}s")
print(f"set membership: {set_time:.4f}s")Three details in this example matter.
- The statement is a string, not a function call.
timeitcompiles it and runs it inside a loop. globals=globals()lets the snippet see the namesitems_listanditems_set. Without it, the snippet runs in an empty namespace and you get aNameError.- The value
9_999is the last element of the list, so the list search must scan all 10,000 items. A set finds it with one hash lookup. The set is far faster, and the gap grows as the collection grows.
The returned number is the total for all 1,000 runs. To get the cost of one run, divide by number.
Using setup and callables
Anything that should not be timed belongs in the setup argument, which runs once before the loop.
import timeit
setup = "data = list(range(10_000))"
seconds = timeit.timeit("sorted(data)", setup=setup, number=500)
print(f"sorted on sorted input: {seconds / 500 * 1e6:.1f} microseconds per call")You can also pass a function instead of a string. This is often easier to read and lets your editor check the code.
import timeit
def build_squares():
return [i * i for i in range(1_000)]
seconds = timeit.timeit(build_squares, number=2_000)
print(f"{seconds / 2_000 * 1e6:.1f} microseconds per call")Taking the best of several runs
timeit.repeat runs the whole measurement several times and returns a list of totals. Take the minimum, as the previous section explained.
import timeit
items_list = list(range(10_000))
runs = timeit.repeat(
"9_999 in items_list",
globals=globals(),
repeat=5,
number=1_000,
)
best = min(runs)
print(f"all runs: {[round(r, 4) for r in runs]}")
print(f"best per call: {best / 1_000 * 1e6:.2f} microseconds")If the five numbers differ by a large factor, your machine was busy. Close other programs and run it again before you trust any comparison.
The command-line interface
For a quick check you do not need a script. The -m timeit form picks a sensible number automatically, repeats five times, and prints the best result.
python -m timeit -s "items = list(range(10_000))" "9_999 in items"
python -m timeit -s "items = set(range(10_000))" "9_999 in items"The -s option is the setup statement. The output looks like 20000 loops, best of 5: 98.3 usec per loop. The exact numbers will differ on your machine.
Choosing between the tools
Timing tools answer "how long does this code take?" They do not answer "which code should I time?" For that you need a profiler, which the next chapter introduces.
Common errors
- Timing the setup. If you build a 10,000-item list inside the timed statement, you measure list construction as well as the lookup. Put construction in
setupor outside the call. - Forgetting
globals=globals(). The snippet raisesNameErrorbecausetimeitruns it in a fresh namespace. - Letting the work be optimized away in your head. A snippet such as
x = 2 + 2is folded to a constant by the compiler, so you measure nothing. Use values that come from variables. - Comparing results that differ in correctness. Make sure both versions return the same answer before you compare speed. An
asserton the results costs nothing. - Timing with
printinside the loop. Output to a terminal can be slower than the code you are measuring. - Trusting a single run. Use the minimum of
repeatresults, not the first number you see. - Mutating shared data. If the statement changes its input, such as
data.sort()ordata.append(1), later iterations see different data. Sorting an already sorted list is much faster than sorting a shuffled one. Rebuild the input insetupwithrepeat, or copy it inside the statement and accept the copy cost for both versions.
Summary of the working model
Use perf_counter to time larger blocks and anything you want to report to the user. Use timeit for small snippets that need thousands of runs. Always separate setup from the timed statement. Repeat the measurement and keep the minimum. Check that the versions you compare produce the same result. Treat every number as specific to one machine and one Python version.
Exercise
A colleague times two versions of a function once each with time.time() and reports that version B is 3% faster. Name two problems with this measurement and say what you would change.
Show answer
First, time.time() is not monotonic and has coarser resolution on some systems, so use time.perf_counter(). Second, a single run per version is dominated by noise such as CPU contention and cold caches, and a 3% difference is likely within that noise. Use timeit.repeat with several repeats, compare the minimum for each version, and check that both versions return the same result.
Exercise
This code raises NameError: name 'numbers' is not defined. Fix it, then explain how you would also stop the list construction from being included in the timing. import timeit numbers = list(range(1000)) print(timeit.timeit("sum(numbers)", number=10000))
Show answer
Pass the module namespace with globals=globals(): timeit.timeit("sum(numbers)", globals=globals(), number=10_000). The list is built once on the line above the call, outside the timed statement, so its construction is already excluded. If the list had to be built per run, build it in the setup argument or in a helper that is not part of the timed statement.