Performance Profiling

Concepts covered: Data Types

The byte counts above came from a measurement, and every claim about speed or memory should come the same way. The standard library covers both sides: time.perf_counter() for elapsed time and sys.getsizeof() for the bytes of one object.

Timing code with perf_counter

perf_counter() returns seconds as a float counted from an arbitrary starting point, so only the difference between 2 calls means anything. A single run is noisy because other processes take CPU time, and that noise only ever adds time. Repeat the measurement several times and keep the minimum: it's the closest estimate of what the code itself costs.

import sys
import time

ids_list = list(range(0, 20000, 2))
ids_set = set(ids_list)
probes = range(1, 2001, 2)

best_list = float("inf")
best_set = float("inf")
for run in range(5):
    start = time.perf_counter()
    hits = sum(1 for p in probes if p in ids_list)
    best_list = min(best_list, time.perf_counter() - start)

    start = time.perf_counter()
    hits = sum(1 for p in probes if p in ids_set)
    best_set = min(best_set, time.perf_counter() - start)

print("hits:", hits)
print("set faster:", best_set < best_list)
print("over 100x faster:", best_list > 100 * best_set)
print("list bytes:", sys.getsizeof(ids_list))
print("set bytes:", sys.getsizeof(ids_set))

Output:

hits: 0
set faster: True
over 100x faster: True
list bytes: 80056
set bytes: 524504

Every probe is odd and every id is even, so all 1,000 lookups miss: the list compares each probe against all 10,000 ids, while the set hashes the probe and checks one slot. The booleans hold on any machine. The raw seconds, which you can print yourself, change with the hardware. The last 2 lines show the bill for that speed: the set needs a hash table with spare room, and it pays for it in bytes.

Why sys.getsizeof is shallow

sys.getsizeof counts the object you hand it and none of the objects it refers to. A list's size is its header plus one 8-byte reference per slot, whether a reference points at a 1-character string or a 10 MB one. To measure a whole structure, walk it and add up every object you reach, counting each object once by its id(), because 2 records can share the same string.

import sys

def deep_size(obj, seen=None):
    if seen is None:
        seen = set()
    if id(obj) in seen:
        return 0
    seen.add(id(obj))
    size = sys.getsizeof(obj)
    if isinstance(obj, dict):
        for key, value in obj.items():
            size += deep_size(key, seen) + deep_size(value, seen)
    elif isinstance(obj, (list, tuple, set)):
        for item in obj:
            size += deep_size(item, seen)
    return size

rows = [{"city": "Lisbon", "nights": 3}, {"city": "Lisbon", "nights": 5}]
print(sys.getsizeof(rows))
print(deep_size(rows))

Output:

72
755

The shallow figure is the list header and 2 references. The deep figure adds both dicts at 232 bytes each, then the keys and values. The 2 "Lisbon" literals are one shared object in this program, and so are the key strings, so seen counts each of them once. Without seen, the walk would report shared strings once per record and overstate the total.

What does this program print?

import sys

small = ["a"]
big = ["a" * 10_000]
print(sys.getsizeof(small) == sys.getsizeof(big))

Trading memory for time, and back

The set bought speed with memory. A generator makes the opposite trade. It holds one value at a time, so its size stays fixed no matter how many values it will yield, but it produces them only once. A second pass over the same generator finds it already exhausted and sees nothing.

import sys

squares_list = [n * n for n in range(1_000_000)]
squares_gen = (n * n for n in range(1_000_000))
print(sys.getsizeof(squares_list))
print(sys.getsizeof(squares_gen))
print(sum(squares_list) == sum(squares_gen))
print(sum(squares_gen))

Output:

8448728
112
True
0
Spend memory to save time
  • A set or dict index beside a list for membership tests
  • A cache holding results of slow calls
  • A materialized list you will read many times
Spend time to save memory
  • A generator that recomputes values on each pass
  • Scanning a list instead of keeping a set index beside it
  • Recomputing a rare result instead of storing it

About this lesson

This section is part of the Data Structures: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.