Skip to content
KALANBLON
Show contents

Chapter 4 of 7 · 20 min

Performance: measure before optimising

By the end of this chapter, you'll be able to

  • Estimate the complexity of a process: O(1), O(n), O(n²)
  • Choose between list, set, dict, deque and heapq depending on the operations
  • Measure with timeit and profile with cProfile before optimising
  • Avoid the classic traps: searching a list, concatenating in a loop

Counting operations

Complexity describes how the work grows when the data grows. Searching for an item in a list means going through it, one comparison per item:

def count_list_search(items, target):
    comparisons = 0
    for x in items:
        comparisons += 1
        if x == target:
            break
    return comparisons

for n in [1_000, 10_000, 100_000]:
    data = list(range(n))
    print(n, "items →", count_list_search(data, n - 1), "comparisons")
1000 items → 1000 comparisons
10000 items → 10000 comparisons
100000 items → 100000 comparisons

Ten times more data, ten times more work: that's linear complexity, written O(n). If you do this search for each item of another list of the same size (a loop inside a loop), you get O(n²): 100,000 × 100,000 = ten billion comparisons. That's why the script never finishes.

A set or a dict finds an item in constant time on average, O(1), thanks to a hash table: the value is turned into a slot number, and Python goes straight to that slot.

The right structure for each need

NeedStructureTypical cost
test membership, remove duplicatessetO(1)
associate a key with a valuedictO(1)
access by positionlistO(1)
add or remove at the startcollections.dequeO(1) (O(n) with a list)
always take the smallestheapqO(log n)
from collections import deque, defaultdict
import heapq

queue = deque(["Ama", "Bao", "Chidi"])
queue.append("Dara")
print(queue.popleft(), list(queue))

by_city = defaultdict(list)
for name, city in [("Ama", "Accra"), ("Bao", "Hanoi"), ("Chidi", "Accra")]:
    by_city[city].append(name)
print(dict(by_city))

tasks = [(3, "archive"), (1, "invoice"), (2, "follow up")]
heapq.heapify(tasks)
print([heapq.heappop(tasks)[1] for _ in range(3)])
Ama ['Bao', 'Chidi', 'Dara']
{'Accra': ['Ama', 'Chidi'], 'Hanoi': ['Bao']}
['invoice', 'follow up', 'archive']

defaultdict(list) automatically creates an empty list for a missing key. heapq maintains a heap: the smallest item (here the lowest priority) always comes out first.

Same answer, but the set's cost doesn't depend on its size.

Step 4 of 4
Text description of the animation
  1. We look for a value placed at the end of the collection.
  2. In a list, Python compares each item until it finds it: 100,000 comparisons.
  3. In a set, Python computes the value's hash and goes straight to the right slot.
  4. Same answer, but the set's cost doesn't depend on its size.

Measure, then profile

You don't guess where the time goes: you measure. timeit times a small piece of code by repeating it:

import timeit

list_data = list(range(100_000))
set_data = set(list_data)

t_list = timeit.timeit(lambda: 99_999 in list_data, number=200)
t_set = timeit.timeit(lambda: 99_999 in set_data, number=200)
print("Search done in both structures")

Display t_list / t_set on your computer: the set is usually hundreds, even thousands of times faster on this example. The exact figures depend on the machine, which is why you always compare two versions on the same machine.

For a whole program, cProfile shows which functions use up the time:

$ python -m cProfile -s cumulative deduplicate.py
   ncalls  tottime  cumtime  filename:lineno(function)
        1    0.002   41.380  deduplicate.py:12(deduplicate)
   100000   41.105   41.105  deduplicate.py:5(already_seen)

Here, already_seen, called 100,000 times, takes almost all the time: that's where, and only where, you should act.

Your turn

Worked exercise

Worked exercise: pairs that make a total

Write a function pairs(amounts, target) that returns, sorted, the pairs of distinct amounts from a list whose sum equals target. A naive version compares each amount with all the others: O(n²). Write an O(n) version with a set. With [500, 1500, 700, 1300, 1000, 2000] and the target 2000, the result is [(500, 1500), (700, 1300)].

Hint 1
For each amount a, the complement you're looking for is target - a. Have you already seen that complement?
Hint 2
Keep the amounts already seen in a set; when the complement is in it, store the sorted pair (min, max) in another set to avoid duplicates.
Show the solution and common mistakes
def pairs(amounts, target):
    seen = set()
    result = set()
    for a in amounts:
        complement = target - a
        if complement in seen and complement != a:
            result.add((min(a, complement), max(a, complement)))
        seen.add(a)
    return sorted(result)

print(pairs([500, 1500, 700, 1300, 1000, 2000], 2000))
print(pairs([1000, 1000], 2000))
[(500, 1500), (700, 1300)]
[]

Each amount is handled only once, with two O(1) operations on sets: O(n) in total.

Common mistakes:

  • Forgetting the condition complement != a: 1000 + 1000 would give the pair (1000, 1000) when we want two distinct amounts.
  • Adding a to seen before looking for its complement: an amount equal to half the target would find itself.

Summary

  1. 1Complexity describes how the work grows with the data: O(1), O(n), O(n²).
  2. 2set and dict find an item in O(1); a list has to be gone through.
  3. 3deque, defaultdict and heapq cover the common needs at the right cost.
  4. 4Measure with timeit and profile with cProfile before optimising.
  5. 5Searching a list in the heart of a loop gives O(n²).

Your progress is saved on this device. Create a free account to keep your progress on all your devices.