Python Testing and Debugging · Lesson 131 of 149

Python Timing and Profiling

What you will learn

  • Why to measure before optimising
  • Timing with perf_counter and timeit
  • Finding bottlenecks with cProfile
  • How time grows with input size
  • Measuring memory: tracemalloc, sys.getsizeof
  • A sensible optimisation workflow

1. Measure first

"Premature optimisation is the root of all evil." This famous remark (by Donald Knuth) warns against making code complicated for speed you have not shown to be needed.

Programmers are bad at guessing which part of a program is slow. The rule:

  1. Make it correct (with tests, lesson 18.4).
  2. Measure whether it is too slow at all.
  3. Find the part where the time goes (profile).
  4. Change that part, and measure again.

Most of the time a program spends is in a small part of the code. Speeding up the other 90 percent changes nothing. A better algorithm or data structure (lesson 7.7 on lists, lesson 9.7 on hashing) beats clever tricks.

Timing numbers depend on the computer. All the timings below come from one Windows laptop; your numbers will differ, and the same code varies from run to run. Compare numbers from the same machine, and look at the ratios.

Quick check: what should come before optimising a slow program?

Measuring and finding where the time actually goes.

2. Timing with perf_counter

time.perf_counter() is a high-precision clock (lesson 17.1). Take it before and after:

import time

start = time.perf_counter()
result = sum(range(1_000_000))
elapsed = time.perf_counter() - start
print(f"{elapsed * 1000:.1f} ms")

One measurement is noisy (other programs, caches, a first-run effect). It is better to repeat and take the fastest run, which is the least disturbed by outside noise. The timeit module does exactly that.

3. timeit

timeit runs a snippet many times and reports the total time:

import timeit

t = timeit.timeit("sum(range(1000))", number=2000)
print(type(t).__name__)

runs = timeit.repeat("sum(range(100))", number=100, repeat=3)
print(len(runs))
float
3
  • timeit.timeit(code, number=n) returns the seconds taken for n runs, as a float.
  • timeit.repeat(code, number=n, repeat=r) does that r times and returns a list: use min(...) of it.
  • code can be a string of Python, or a function (such as lambda: f(x)), which avoids quoting trouble.
  • From the command line: python -m timeit "sum(range(1000))" chooses a sensible number of runs and prints the best.

Comparing alternatives

Three ways to build a long string of numbers (20,000 of them, best of 5 repeats of 20 runs, on the check computer):

def concat(n):
    s = ""
    for i in range(n):
        s += str(i)
    return s

def join(n):
    return "".join(str(i) for i in range(n))

def join_list(n):
    return "".join([str(i) for i in range(n)])

for f in (concat, join, join_list):
    print(f.__name__, round(min(timeit.repeat(lambda: f(20000), number=20, repeat=5)), 4))
concat 0.0642
join 0.0387
join_list 0.0301

Joining a list was about twice as fast as repeated += (lesson 4.7), and slightly faster than joining a generator. Another famous gap is membership testing (lesson 9.7):

data_list = list(range(20000))
data_set = set(data_list)
a = min(timeit.repeat(lambda: 19999 in data_list, number=200, repeat=5))
b = min(timeit.repeat(lambda: 19999 in data_set, number=200, repeat=5))
print(round(a / b))
2262

On this computer, checking the last item of a 20,000-item list took about 2,000 times longer than the same check in a set: the list scans every item, the set jumps straight to it. (The exact ratio varies; the size of the gap is the lesson.) And a list comprehension (lesson 12.1) was faster than the equivalent loop with append in the check (the comparison printed True).

Timing pitfalls:

  • Time the realistic input size, not tiny examples.
  • Do not time print or file input/output unless that is the point.
  • Run it several times; use the minimum.
  • Do not compare numbers from different computers.

4. Profiling: where does the time go?

When a whole program is slow, timeit on pieces is a guess. A profiler measures every function call and shows where the time goes. Python includes cProfile:

import cProfile
import io
import pstats

profile = cProfile.Profile()
profile.enable()
find_duplicates_slow(data)          # the code to examine
profile.disable()

out = io.StringIO()
pstats.Stats(profile, stream=out).sort_stats("tottime").print_stats(3)
print(out.getvalue())

From the command line, python -m cProfile -s cumulative script.py profiles a whole script. The report columns:

Column Meaning
ncalls how many times the function was called
tottime time spent inside the function itself, excluding the functions it calls
cumtime time inside the function including the functions it calls
percall the above divided by the number of calls

Sort by tottime to find the function that burns time itself; sort by cumulative to see which high-level call is responsible. For a program that spreads time thinly over many functions, the report shows that no single fix will help.

Profiling slows the program a little, and the profile of a different input can differ, so profile with realistic data.

5. How time grows

What matters most is how running time grows with the size of the input. Doubling the input should ideally double the time, not quadruple it. The slow duplicate finder below checks, for every item, whether it appears in the part of the list before it (a scan). Timing it for 1,000, 2,000 and 4,000 items:

1000 4.1 ms
2000 15.0 ms
4000 58.0 ms

Each doubling of the input multiplied the time by about four: quadratic growth ("O(n²)"). At 100,000 items the program would take minutes. A version that does the work in one pass using a set grows in step with the input ("O(n)", linear). The common growth rates:

Growth Name Example
constant O(1) dict lookup, set membership, list.append
logarithmic O(log n) binary search in sorted data
linear O(n) one loop over the data, x in list
n log n O(n log n) sorted
quadratic O(n²) a loop inside a loop over the same data

6. Memory

Speed is not the only cost. tracemalloc measures memory that Python allocates:

import tracemalloc

tracemalloc.start()
data = [str(i) * 10 for i in range(50000)]
current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
print(round(current / 1e6, 1), "MB currently", round(peak / 1e6, 1), "MB peak")
4.9 MB currently 4.9 MB peak

sys.getsizeof(obj) gives the size of one object, not counting what it refers to:

import sys

print(sys.getsizeof([]), sys.getsizeof(list(range(1000))), sys.getsizeof(set()))
print(sys.getsizeof("a"), sys.getsizeof(1))
print(sys.getsizeof(range(10**9)), sys.getsizeof((i for i in range(10**9))))
56 8056 216
42 28
48 192

An empty list takes 56 bytes, a 1,000-item list about 8 KB (for its pointers). Notice the last line: a range of a billion numbers and a generator of a billion numbers take only 48 and 192 bytes, because they produce values on demand (lessons 12.6 and 12.7). When memory is the problem, think generators, iterators, smaller types, and processing in chunks.

Worked example: speeding up a duplicate finder

A function lists the values that occur more than once. We time both versions on 3,000 random numbers, profile the slow one, and confirm that the results agree.

import cProfile
import io
import pstats
import timeit
import random


def find_duplicates_slow(items):
    dupes = []
    for i, x in enumerate(items):
        if x in items[:i] and x not in dupes:
            dupes.append(x)
    return dupes


def find_duplicates_fast(items):
    seen, dupes = set(), set()
    for x in items:
        if x in seen:
            dupes.add(x)
        seen.add(x)
    return sorted(dupes)


random.seed(7)
data = [random.randint(1, 3000) for _ in range(3000)]
assert sorted(find_duplicates_slow(data)) == find_duplicates_fast(data)

for name, func in [("slow", find_duplicates_slow), ("fast", find_duplicates_fast)]:
    best = min(timeit.repeat(lambda: func(data), number=1, repeat=3))
    print(f"{name}: {best * 1000:.1f} ms")

profile = cProfile.Profile()
profile.enable()
find_duplicates_slow(data)
profile.disable()
out = io.StringIO()
pstats.Stats(profile, stream=out).sort_stats("tottime").print_stats(3)
for line in [l for l in out.getvalue().splitlines() if l.strip()][:6]:
    print(line)

Output on the check computer (timings differ on yours):

slow: 34.3 ms
fast: 0.3 ms
         793 function calls in 0.033 seconds
   Ordered by: internal time
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.033    0.033    0.033    0.033 w185.py:8(find_duplicates_slow)
      791    0.000    0.000    0.000    0.000 {method 'append' of 'list' objects}
Finding Meaning
assert ... == first a faster function that gives wrong answers is useless: check the results agree
slow 34.3 ms, fast 0.3 ms the set version is about a hundred times faster at this size, and the gap grows with the input
the profile all of the time (0.033 s) is inside find_duplicates_slow itself, not in append or other calls; the profiler works per function, so it points at the function, and reading the code points at the x in items[:i] line
why it is slow items[:i] copies part of the list and in scans it, for every item: quadratic growth
why the fix works a set answers "have I seen this?" in about constant time

The numbers are made up from random data, and the timings are specific to the computer used. The point of the workflow: measure, find the cause, change one thing, measure again.

Common mistakes

  • Optimising before measuring.
  • Timing a single run, or tiny inputs.
  • Comparing timings from different machines or while other heavy programs run.
  • Making code unreadable for small gains.
  • Ignoring the algorithm (a list scan inside a loop) and tuning details instead.
  • Forgetting to check the faster version gives the same answers.
  • Profiling with unrealistic data.
  • Timing code that includes print or file reads unintentionally.

Key takeaways

  • Make it correct, then measure, then optimise the part that matters, then measure again.
  • time.perf_counter times a block; timeit repeats a snippet (use the minimum of repeat); timings only compare on the same computer.
  • cProfile shows which functions use the time (tottime itself, cumtime including callees).
  • Look at how time grows with input size: a loop inside a loop is quadratic; sets and dictionaries make membership checks fast.
  • tracemalloc and sys.getsizeof measure memory; generators and iterators save it.
  • Always verify that the optimised code still gives the right answers.

Practice

1. Why take the min of timeit.repeat results?

Show answer

Other activity on the computer can only slow a run down, so the fastest run is the one least disturbed by noise.

2. What is the difference between tottime and cumtime?

Show answer

tottime is time spent inside the function itself; cumtime also includes the time in the functions it calls.

3. If doubling the input makes a program four times slower, how does its time grow?

Show answer

Quadratically (O(n²)).

4. Why is x in some_set so much faster than x in some_list for big collections?

Show answer

A set uses hashing to find the item directly, while a list compares with its items one by one.

5. How can you reduce the memory used when processing a huge file?

Show answer

Read it line by line or in chunks and use generators, instead of loading everything into one list.

6. Why check that an optimised function returns the same results?

Show answer

Speed is worthless if the answers are wrong; a test or an assert comparing old and new versions catches mistakes introduced by the rewrite.