Performance and profiling
First measure, then optimise: use timeit for small snippets and cProfile to find which functions take the time. The biggest wins usually come from better data structures (a set instead of a list for lookups), built-in functions, caching repeated work and moving number crunching to NumPy — not from clever tricks.
Measure with timeit
import timeit
loop = timeit.timeit("s = 0\nfor i in range(1000): s += i", number=2000)
builtin = timeit.timeit("sum(range(1000))", number=2000)
print(f"loop is {loop / builtin:.0f}x slower than sum()" if loop > builtin else "sum() was not faster")Press Run to measure on your own device. Built-ins like sum, min, max, sorted and "".join run in C and are usually several times faster than an equivalent Python loop.
The right data structure
import timeit
setup = "items_list = list(range(100_000)); items_set = set(items_list)"
in_list = timeit.timeit("99_999 in items_list", setup=setup, number=200)
in_set = timeit.timeit("99_999 in items_set", setup=setup, number=200)
print(in_set < in_list)
print(f"set lookup about {in_list / in_set:,.0f}x faster")| Task | Slow | Fast |
|---|---|---|
| Is x in a big collection? | x in list | x in set or dict |
| Add/remove at the front | list.insert(0, x) | collections.deque |
| Count things | nested loops | collections.Counter |
| Build a long string | s += part in a loop | "".join(parts) |
| Find the top 3 of a million | sorted(x)[:3] | heapq.nlargest(3, x) |
Cache repeated work
from functools import cache
import time
@cache
def exchange_rate(currency: str) -> float:
time.sleep(0.2) # pretend slow lookup
return {"USD": 1.08, "INR": 90.1}[currency]
prices = [exchange_rate("USD") * p for p in [10, 20, 30, 40]]
print([round(p, 2) for p in prices])
print(exchange_rate.cache_info().misses, "slow lookup")[10.8, 21.6, 32.4, 43.2] 1 slow lookup
Find the slow part with cProfile
import cProfile
import pstats
def slow_unique(items):
seen = []
for x in items:
if x not in seen: # list lookup: slow
seen.append(x)
return seen
def report():
data = list(range(3000)) * 2
return len(slow_unique(data))
profiler = cProfile.Profile()
profiler.enable()
result = report()
profiler.disable()
print(result)
stats = pstats.Stats(profiler).sort_stats("cumulative")
top = [name for (_, _, name) in list(stats.stats)][:5]
print("slow_unique" in top)3000 True
$ python -m cProfile -s cumulative report.py | head -8The profile shows how much time each function took, including the functions it calls. Fix the top entry first; changing anything else is guesswork.
Vectorise number crunching
import numpy as np
prices = np.array([12.5, 8.0, 30.0, 4.25])
with_vat = prices * 1.21
print(with_vat.round(2))
print(round(float(with_vat.sum()), 2))[15.12 9.68 36.3 5.14] 66.25
NumPy applies one operation to a whole array in C, typically 10–100 times faster than a Python loop over the same numbers. The Python for AI path covers it in depth.
Practice
Speed up this de-duplication. Write unique_in_order(items) that keeps the first occurrence of each item in its original order, using a set to remember what you've seen. Print the result for [3, 1, 3, 2, 1, 4], then the length of the result for list(range(50_000)) * 2.
[3, 1, 2, 4] 50000