Performance and profiling
Course contents (15 lessons)
- Iteration the Python way
- List, dict and set comprehensions
- Iterators and generators
- Functions as building blocks
- Closures and decorators
- Context managers and the with statement
- Object-oriented Python in depth
- Classes and dataclasses
- Properties and special (dunder) methods
- Inheritance versus composition
- Quality: types, packaging and tests
- Type hints and mypy
- Packaging a project with pyproject.toml
- Testing with pytest
- Async code and web APIs
- async and await with asyncio
- Working with HTTP APIs and JSON
- Performance, concurrency and a final project
- Performance and profiling
- Concurrency: threads versus processes
- Final project: a price tracker command-line tool
Measure first
The most expensive mistake in performance work is optimising the wrong thing. Programmers are bad at guessing where time goes. I once spent a day speeding up a parsing function, only to find that the program spent 90 percent of its time waiting for a database query on the line before. So the first rule: measure, then change one thing, then measure again.
timeit for small snippets
The timeit module runs a small piece of code many times and reports a reliable time.
import timeit
setup = "data = list(range(100_000)); target = 99_999"
print(timeit.timeit("target in data", setup=setup, number=200))
setup_set = "data = set(range(100_000)); target = 99_999"
print(timeit.timeit("target in data", setup=setup_set, number=200))
The numbers depend on your computer, but the set version will be thousands of times faster. A list checks every item one by one, which takes time proportional to its length. A set uses hashing and answers in roughly constant time. That single difference, list versus set for membership tests, is behind a huge share of slow Python code.
cProfile for whole programs
When you do not know which function is slow, use the profiler. It records how much time each function takes.
import cProfile
import pstats
import time
def load_orders(n):
return [{"id": i, "customer": i % 500, "amount": i % 97} for i in range(n)]
def slow_totals(orders):
totals = {}
for order in orders:
# BAD: scans the whole list of customers for each order
customers = [o["customer"] for o in orders]
if order["customer"] in customers:
totals[order["customer"]] = totals.get(order["customer"], 0) + order["amount"]
return totals
def fast_totals(orders):
totals = {}
for order in orders:
key = order["customer"]
totals[key] = totals.get(key, 0) + order["amount"]
return totals
def run():
orders = load_orders(2_000)
slow_totals(orders)
fast_totals(orders)
if __name__ == "__main__":
profiler = cProfile.Profile()
profiler.enable()
run()
profiler.disable()
pstats.Stats(profiler).sort_stats("cumulative").print_stats(8)
Reading the output
The report has columns: ncalls is how many times a function ran, tottime is the time spent inside that function alone, and cumtime includes the functions it called. Sort by cumulative time to see which top-level call is expensive, then look at tottime to find the real culprit. In our run slow_totals will dominate, and a listcomp inside it will show up as the hot line, since it rebuilds a 2,000-item list 2,000 times. That is 4 million steps for a job that needs 2,000.
You can also run the profiler from the command line without changing code: python -m cProfile -s cumulative myscript.py. For a visual view, tools like snakeviz draw the result as a chart. For line-by-line detail, line_profiler helps. And tracemalloc, in the standard library, finds memory problems.
Common fixes, in order of impact
- A better algorithm or data structure. This beats everything else. Replace list lookups with sets or dicts. Avoid nested loops over big data.
- Do less work. Move calculations out of loops. Read a file once instead of many times. Stop early with
any()orbreak. - Cache repeated results. Use
functools.lru_cachefor pure functions, as in the decorators lesson. - Use built-ins and the standard library.
sum,sorted,str.joinand thecollectionsmodule are written in C and fast. - Use the right tool for big numeric work. NumPy or pandas process arrays in compiled code and can be 50 times faster than loops.
- Do the work in parallel. Covered in the next lesson.
String building
A classic example: joining many strings with += in a loop copies the text over and over in the worst case. Collect the pieces in a list and call "".join(pieces) once at the end.
parts = []
for i in range(10_000):
parts.append(f"line {i}")
text = "\n".join(parts)
Common mistakes
- Optimising early. Clear code that is fast enough is better than clever code that is slightly faster. Profile only when there is a real problem.
- Timing a single run. One run is noisy because of caches and other programs. Repeat, and use
timeit. - Profiling with tiny data. A problem that grows with data size only shows up with realistic amounts.
- Forgetting I/O. If the time is in the network or the disk, faster Python code will not help. Cache, batch requests, or use async.
- Trusting a benchmark from the internet. Results depend on your data, version and machine.
Try it yourself
Write two functions that find duplicate email addresses in a list of 50,000 strings: one using a nested loop and one using a set. Measure both with timeit on lists of 1,000, 5,000 and 20,000 items, and notice how the first grows much faster than the second. Then profile your slower function with cProfile and find the exact line responsible.
import cProfile
import pstats
import time
def load_orders(n):
return [{"id": i, "customer": i % 500, "amount": i % 97} for i in range(n)]
def slow_totals(orders):
totals = {}
for order in orders:
# BAD: scans the whole list of customers for each order
customers = [o["customer"] for o in orders]
if order["customer"] in customers:
totals[order["customer"]] = totals.get(order["customer"], 0) + order["amount"]
return totals
def fast_totals(orders):
totals = {}
for order in orders:
key = order["customer"]
totals[key] = totals.get(key, 0) + order["amount"]
return totals
def run():
orders = load_orders(2_000)
slow_totals(orders)
fast_totals(orders)
if __name__ == "__main__":
profiler = cProfile.Profile()
profiler.enable()
run()
profiler.disable()
pstats.Stats(profiler).sort_stats("cumulative").print_stats(8)
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account