Skip to content

15. Performance and concurrency

A report that takes 2 seconds is fine. The same report on a 50 times bigger file takes almost 2 minutes, or 2 hours if the code hides a quadratic loop. This module teaches you to find out why code is slow and to fix the right thing. You measure first, with timeit and cProfile. Then you fix the slow part: a better algorithm, a better data structure, or work that runs at the same time on threads, processes or an event loop.

Timings change from machine to machine and from run to run. So this page prints comparisons (set is faster: True), operation counts and call counts. Where a duration is the point, the Output shows the duration of one run on a laptop. Your numbers will differ. The comparisons will not.

  • Use big-O notation to predict how code scales, and check the prediction by counting operations and timing real runs.
  • Time code correctly with time.perf_counter(), timeit.timeit(), timeit.repeat() and python -m timeit.
  • Find the slow functions of a data pipeline with cProfile and pstats, sort by cumulative time and fix the hotspot.
  • Choose data structures for speed: set and dict for lookups, deque for queues and a dict index instead of a nested-loop join.
  • Explain the GIL in plain words and choose between threading, multiprocessing and asyncio for I/O-bound and CPU-bound work.
  • Run work concurrently with ThreadPoolExecutor, ProcessPoolExecutor and asyncio (asyncio.run, gather, Semaphore), with results in a fixed order.

Make it work, then measure, then make it fast

Section titled “Make it work, then measure, then make it fast”

Performance is how much time and memory a program needs for its job. Most code is fast enough. A slow program is usually slow in one or two places. Such a place is a hotspot (or bottleneck): the part of the code where most of the time goes.

The order of work matters:

  1. Make the code correct, with tests (module 14).
  2. Measure it on realistic data. A benchmark is a repeatable measurement of how long code takes.
  3. If it is too slow, profile it: measure where the time goes, function by function.
  4. Fix the hotspot. Then run the tests and measure again.
flowchart TD
    A["Correct code + tests"] --> B["Measure on real data"]
    B --> C{"Fast enough?"}
    C -->|yes| D["Stop"]
    C -->|no| E["Profile: find the hotspot"]
    E --> F["Fix it: algorithm, data structure,<br/>vectorize or run concurrently"]
    F --> G["Run the tests"]
    G --> B

Do not guess. Programmers are famously bad at guessing where the time goes. A rewrite of the wrong function costs a day and saves nothing.

Module 04 introduced big-O notation: a way to say how the work of an algorithm grows with the size of its input, n. Big-O ignores constant factors and small terms. It answers one question: when the data gets 10 times bigger, how much slower does the code get?

Big-O Name Data example n = 1,000 n = 1,000,000
O(1)O(1) constant look up a customer in a dict 1 1
O(log⁡n)O(\log n) logarithmic binary search in a sorted list of prices 10 20
O(n)O(n) linear sum the revenue column 1,000 1,000,000
O(nlog⁡n)O(n \log n) linearithmic sort order lines by revenue 10,000 20,000,000
O(n2)O(n^2) quadratic compare every customer with every other customer 1,000,000 1,000,000,000,000

The last two columns count steps, roughly. Logarithmic time means that the work grows by one step each time the data doubles: log⁡21,000,000≈20\log_2 1{,}000{,}000 \approx 20. Linearithmic time (nlog⁡nn \log n) is the cost of a good sort. It is a little more than linear. Quadratic time is the danger: a nested loop over the same data. It feels fine on 1,000 rows and never finishes on a million.

The numbers come from three formulas. You can compute them yourself:

import math
print(f"{'n':>9} {'log2 n':>7} {'n log2 n':>12} {'n^2':>17}")
for n in (10, 1_000, 1_000_000):
print(f"{n:>9,} {math.log2(n):>7.1f} {n * math.log2(n):>12,.0f} {n**2:>17,}")
Output
n log2 n n log2 n n^2
10 3.3 33 100
1,000 10.0 9,966 1,000,000
1,000,000 19.9 19,931,569 1,000,000,000,000

Big-O usually describes the worst case (the slowest input) or the average case. Searching a list is O(n)O(n): on average, you look at half the items, and in the worst case at all of them. The constant “half” disappears in big-O, because it does not change how the work grows.

Python’s built-in types have known costs. Learn this table. It explains most slow scripts.

Operation list dict / set collections.deque
x in container O(n)O(n): scans every item O(1)O(1) average: one hash lookup O(n)O(n)
get by position c[i] O(1)O(1) — O(n)O(n) in the middle, O(1)O(1) at the ends
get by key d[key] — O(1)O(1) average —
add at the end (append, add, d[k] = v) O(1)O(1) amortized O(1)O(1) average O(1)O(1)
add or remove at the front (insert(0, x), pop(0)) O(n)O(n): moves every item — O(1)O(1) (appendleft, popleft)
remove the last item pop() O(1)O(1) — O(1)O(1)
len(c) O(1)O(1) O(1)O(1) O(1)O(1)
sort sorted(c) O(nlog⁡n)O(n \log n) O(nlog⁡n)O(n \log n) (makes a list) O(nlog⁡n)O(n \log n) (makes a list)
build from n items O(n)O(n) O(n)O(n) O(n)O(n)

“Average” matters for dicts and sets. A hash table (module 04) is O(1)O(1) when the hashes spread well, which is true for strings, numbers and tuples. “Amortized” means “averaged over many calls”: a list sometimes grows its storage, but the average cost of append stays constant.

time.perf_counter() returns the value of a high-resolution clock, in seconds. One value alone means nothing. The difference between two values is the elapsed time. This is wall-clock time: the time that passes on a clock on the wall, including time spent waiting.

time.process_time() measures CPU time: the time the processor spends running your process. Waiting for a network, a disk or time.sleep() costs wall-clock time but almost no CPU time. The gap between the two tells you what kind of slow you have:

wall_vs_cpu.py
import time
def simulated_download() -> None:
time.sleep(0.2) # waiting, like a network call
def busy_sum() -> int:
return sum(i * i for i in range(2_000_000)) # computing
for task in (simulated_download, busy_sum):
wall_start, cpu_start = time.perf_counter(), time.process_time()
task()
wall = time.perf_counter() - wall_start
cpu = time.process_time() - cpu_start
kind = "mostly waits" if cpu < wall / 10 else "mostly computes"
print(f"{task.__name__:<18} wall {wall:.2f} s cpu {cpu:.2f} s {kind}")
Output
simulated_download wall 0.21 s cpu 0.00 s mostly waits
busy_sum wall 0.08 s cpu 0.08 s mostly computes

The download waits: its wall time is large and its CPU time is near zero, below a tenth of the wall time. The sum computes: both times are about equal. Code that spends most of its time waiting is I/O-bound (I/O means input/output: network, disk, database). Code that spends most of its time computing is CPU-bound. This difference decides which concurrency tool helps, later on this page.

Do not use time.time() for measurements. It follows the system clock, which can jump when the computer syncs its time.

A single perf_counter() measurement of fast code is noisy. Other programs run, the CPU changes speed, and the first run is often slower. The timeit module fixes this. It runs the code many times, uses the best clock and switches off the garbage collector during the run. A micro-benchmark is a benchmark of one small piece of code, such as one function call.

timeit.timeit(stmt, number=N) runs stmt N times and returns the total time in seconds. stmt is a string of code or a function with no arguments, often a lambda. Compare a hand-written loop with the built-in sum() on the revenue column of data/sales.csv:

import csv
import timeit
with open("data/sales.csv", newline="", encoding="utf-8") as f:
revenues = [float(row["revenue"]) for row in csv.DictReader(f)]
def loop_total(values: list[float]) -> float:
total = 0.0
for value in values:
total += value
return total
loop_s = timeit.timeit(lambda: loop_total(revenues), number=100) / 100
sum_s = timeit.timeit(lambda: sum(revenues), number=100) / 100
print(f"loop: {loop_s * 1000:.3f} ms per call")
print(f"sum(): {sum_s * 1000:.3f} ms per call")
print("sum() is faster:", sum_s < loop_s)
Output
loop: 0.150 ms per call
sum(): 0.030 ms per call
sum() is faster: True

sum() runs its loop in C, inside the interpreter, so it skips the work that each Python-level loop step costs. Divide the total by number to get the time per call.

The two totals also differ, which surprises many people:

print(loop_total(revenues))
print(sum(revenues))
Output
3596523.8300009277
3596523.83

Since Python 3.12, sum() of floats uses compensated summation (module 13): it keeps track of the rounding error of each addition and corrects for it. The plain loop collects tiny float errors (module 01). Faster and more accurate: prefer the built-in.

timeit.repeat() runs the whole measurement several times and returns a list. Take the minimum: it is the run with the least disturbance from other programs. The other runs are not “more true”; they include noise. With a string statement, pass globals=globals() so the code can see your variables:

times = timeit.repeat("sum(revenues)", globals=globals(), repeat=5, number=200)
best = min(times) / 200
print(f"best of 5: {best * 1e6:.1f} µs per call")
Output
best of 5: 30.3 µs per call

From the terminal, python -m timeit does the same work and chooses number for you, so that each run lasts at least 0.2 seconds:

Terminal
python -m timeit -s "values = list(range(20_228))" "sum(values)"
python -m timeit -s "ids = set(range(100_000))" "99_999 in ids"

It prints one line per statement, such as 5000 loops, best of 5: 52.1 usec per loop. -s is the setup code: it runs once and is not timed. In Jupyter notebooks, the %timeit command does the same.

timeit tells you how long code takes. A profiler tells you where the time goes. cProfile is the profiler in the standard library. It is a deterministic profiler: it records every function call and every return, with the time between them. pstats reads the records and sorts and prints them.

Profile a whole script from the terminal:

Terminal
python -m cProfile -s cumulative report.py # print the profile after the run
python -m cProfile -o report.prof report.py # save it to a file for pstats

Or profile one part of a program in code:

import cProfile
import pstats
with cProfile.Profile() as profiler: # record every call inside the block
result = monthly_profit("data/sales.csv", "data/products.csv")
stats = pstats.Stats(profiler)
stats.strip_dirs() # show file names without their folders
stats.sort_stats(pstats.SortKey.CUMULATIVE) # slowest call trees first
stats.print_stats(8) # only the top 8 lines

This is a real profile of the code of Example 3, saved as report.py, from one run with Python 3.13 on a laptop. The call counts of your own functions are exact. The times, the line numbers, the library rows and the total depend on your machine, your file and your Python version:

Sample profile (one run, times vary)
673685 function calls (673544 primitive calls) in 0.190 seconds
Ordered by: cumulative time
List reduced from 293 to 8 due to restriction <8>
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.011 0.011 0.190 0.190 report.py:24(monthly_profit)
20228 0.005 0.000 0.133 0.000 report.py:13(month_of)
20228 0.006 0.000 0.109 0.000 {built-in method strptime}
20228 0.008 0.000 0.101 0.000 _strptime.py:786(_strptime_datetime)
20228 0.050 0.000 0.094 0.000 _strptime.py:516(_strptime)
20260 0.018 0.000 0.036 0.000 csv.py:174(__next__)
20230 0.002 0.000 0.020 0.000 _strptime.py:29(_getlang)
20266 0.020 0.000 0.020 0.000 {method 'strftime' of 'datetime.date' objects}
Column Meaning
ncalls how many times the function was called. 3/1 means 3 calls, 1 of them not recursive.
tottime time spent in the function itself, without the functions it calls
percall (first) tottime / ncalls
cumtime cumulative time: time in the function and everything it calls
percall (second) cumtime / ncalls
filename:lineno(function) where the function is defined

Read a profile in two passes:

  • Sort by cumulative to see which call tree is expensive. The top line is your entry point. Go down until you reach a function of your own that has a large cumtime. Here it is month_of: 0.133 of 0.190 seconds, and almost all of it is inside strptime.
  • Sort by tottime (SortKey.TIME) to see which single function burns the CPU itself.

Two warnings. First, the profiler slows code down, more so for code with many tiny calls. Use the profile to find the hotspot; use timeit to measure the fix. Second, ncalls is exact and does not depend on the machine. A function called 20,228 times for 20,228 rows is normal. A function called 400 million times for 20,228 rows is a quadratic loop.

Other profilers exist: py-spy is a sampling profiler (it looks at the program many times per second instead of recording every call, so it adds little overhead), and line_profiler times each line of one function. cProfile needs no install, so start with it.

The fastest code does less work. The right data structure removes work. Each row of this table is a fix that turns O(n)O(n) per operation into O(1)O(1) or O(log⁡n)O(\log n):

Task Slow choice Fast choice Why
“Is this product ID valid?” many times pid in id_list pid in id_set hash lookup instead of a scan
Find a record by its key loop over a list of dicts index = {r["id"]: r for r in rows} once, then index[key] build the index once, O(1)O(1) per lookup
Join two tables nested loops: O(n⋅m)O(n \cdot m) dict index on one table: O(n+m)O(n + m) one pass over each table
A first-in-first-out queue list.pop(0) deque.popleft() no items to move
Count categories labels.count(x) for every x collections.Counter(labels) one pass instead of one per label
Build a long string text += line in a loop "\n".join(lines) one copy instead of many
Keep the 10 largest orders sort the whole list each time heapq.nlargest(10, orders) O(nlog⁡k)O(n \log k) instead of O(nlog⁡n)O(n \log n)
Search a sorted list scan it bisect.bisect_left O(log⁡n)O(\log n) binary search (module 17)
The same expensive call with the same arguments call it again functools.cache (module 09) compute once, then look up
Arithmetic on a whole numeric column Python loop NumPy array operations the loop runs in C (module 23)

A queue shows how large the gap can be. Process 20,228 order lines first-in-first-out:

from collections import deque
def drain_list(items: list[float]) -> int:
queue = list(items)
count = 0
while queue:
queue.pop(0) # moves every remaining item one step left
count += 1
return count
def drain_deque(items: list[float]) -> int:
queue = deque(items)
count = 0
while queue:
queue.popleft() # O(1): nothing moves
count += 1
return count
list_s = timeit.timeit(lambda: drain_list(revenues), number=3) / 3
deque_s = timeit.timeit(lambda: drain_deque(revenues), number=3) / 3
print(drain_list(revenues) == drain_deque(revenues) == 20_228)
print(f"list.pop(0): {list_s * 1000:.1f} ms")
print(f"deque.popleft(): {deque_s * 1000:.1f} ms")
print("deque is faster:", deque_s < list_s)
Output
True
list.pop(0): 18.3 ms
deque.popleft(): 0.5 ms
deque is faster: True

Both functions do 20,228 pops. Each pop(0) moves all remaining items, so the list version does about n2/2≈200n^2 / 2 \approx 200 million item moves. The deque does none.

Some programs are slow because they wait. A script that downloads 100 files spends almost all its time waiting for the network. Other programs are slow because they compute. A bootstrap with 10,000 resamples keeps one CPU core at 100%. Two ideas help, and they are not the same:

  • Concurrency means that several tasks are in progress during the same period. They take turns. While one task waits for the network, another one runs. One CPU core is enough.
  • Parallelism means that several tasks run at the same instant, on different CPU cores. It needs more than one core. A CPU core is one independent processing unit; a laptop has 4 to 16.

A cook who starts the rice, then cuts vegetables while the rice boils, works concurrently. Two cooks who cut vegetables at the same time work in parallel. Concurrency helps I/O-bound work. Only parallelism helps CPU-bound work.

Python gives you three tools:

  • A process is a running program with its own memory. python report.py starts one process. The multiprocessing module starts more.
  • A thread is a sequence of instructions that runs inside a process. All threads of a process share its memory. The threading module starts threads.
  • asyncio runs many tasks in one thread. Each task gives control back while it waits. This is called cooperative multitasking.

The standard Python interpreter, CPython, has a global interpreter lock (GIL). A lock is an object that only one thread can hold at a time. The GIL is the lock that a thread must hold to run Python code. So in one process, only one thread runs Python code at any instant, even on a 16-core machine.

Three facts make the GIL less bad than it sounds:

  1. A thread releases the GIL while it waits: time.sleep(), network calls, file reads and database queries all release it. Other threads run meanwhile. So threads do speed up I/O-bound work.
  2. Many C libraries release the GIL during long computations: NumPy on big arrays, hashlib, compression in zlib. Threads can then run in parallel.
  3. Each process has its own interpreter and its own GIL. So processes do speed up CPU-bound Python code, at the cost of starting processes and copying data to them.

Pure Python computation in threads does not run faster: the threads take turns holding the GIL. Example 6 measures this.

You can check which build you run:

import sys
import sysconfig
free_threaded = bool(sysconfig.get_config_var("Py_GIL_DISABLED"))
gil_enabled = getattr(sys, "_is_gil_enabled", lambda: True)() # 3.13+
print("Free-threaded build:", free_threaded)
print("GIL enabled now:", gil_enabled)
Output
Free-threaded build: False
GIL enabled now: True

sys._is_gil_enabled() exists from Python 3.13. On 3.12 the getattr default returns True, which is correct: 3.12 always has the GIL.

threading / ThreadPoolExecutor multiprocessing / ProcessPoolExecutor asyncio
Best for I/O-bound work with normal (blocking) libraries CPU-bound pure Python work many I/O tasks with async libraries
Runs Python code in parallel no (the GIL), except in free-threaded builds yes, one process per core no, one thread
Memory shared by all threads separate per process shared (one thread)
Passing data direct; protect shared changes with a Lock arguments and results are pickled (copied) direct
Start-up cost small large: a new interpreter per worker very small per task
Useful number tens of threads about one per CPU core thousands of tasks
Switching between tasks the OS and the GIL: between any two bytecodes, at a blocking call or every 5 ms the operating system only at await
Typical use download files, call a REST API with requests, query a database feature engineering, simulations, bootstrap, parsing many files web servers, crawlers, chat apps, httpx.AsyncClient
Main trap race conditions on shared data the main guard, pickling, start-up cost one blocking call freezes every task
flowchart TD
    A["Code is too slow"] --> B{"Mostly waiting or computing?"}
    B -->|"waiting (I/O)"| C{"Async library available?"}
    C -->|yes| D["asyncio"]
    C -->|no| E["ThreadPoolExecutor"]
    B -->|"computing (CPU)"| F{"Can NumPy or pandas do it?"}
    F -->|yes| G["Vectorize (modules 23-25)"]
    F -->|no| H["ProcessPoolExecutor"]

threading.Thread(target=func, args=(...)) creates a thread that will run func(*args). start() starts it. join() waits until it ends. Here 12 threads each check one store’s server, which takes 0.2 seconds of waiting:

import threading
import time
lock = threading.Lock()
stores_checked = 0
def check_store(store_id: str) -> None:
global stores_checked
time.sleep(0.2) # wait for the store's server to answer
with lock: # one thread at a time updates the counter
stores_checked += 1
store_ids = [f"S{n:02d}" for n in range(1, 13)]
threads = [threading.Thread(target=check_store, args=(sid,)) for sid in store_ids]
start = time.perf_counter()
for thread in threads:
thread.start()
for thread in threads:
thread.join()
elapsed = time.perf_counter() - start
print("Stores checked:", stores_checked)
print(f"Elapsed: {elapsed:.2f} s (one after another: {0.2 * len(store_ids):.1f} s)")
print("Waits overlapped:", elapsed < 0.2 * len(store_ids) / 2)
Output
Stores checked: 12
Elapsed: 0.21 s (one after another: 2.4 s)
Waits overlapped: True

All 12 waits overlap, so the whole check takes about as long as one.

The with lock: line matters. stores_checked += 1 is three steps: read the value, add 1, write it back. The interpreter can switch threads between any two steps. If two threads both read 5, both write 6, and one update is lost. This bug is a race condition: the result depends on the timing of threads. It may appear once in a thousand runs, which makes it hard to find. A lock makes the three steps happen as one: a thread that wants the lock waits until the holder releases it.

The best fix is to share nothing. Let each task return its result and collect the results in one place. concurrent.futures works this way.

The concurrent.futures module gives one simple interface for threads and processes. An executor manages a pool of workers: a fixed group of threads or processes that run tasks one after another. You hand it tasks. Two executors exist:

  • ThreadPoolExecutor(max_workers=n): a pool of threads, for I/O-bound work.
  • ProcessPoolExecutor(max_workers=n): a pool of processes, for CPU-bound work.

Both have the same three methods:

Method Does Order of results
pool.map(func, items) runs func(item) for every item; returns an iterator of results the order of items, always
pool.submit(func, *args) starts one task; returns a Future at once —
pool.shutdown() waits for all tasks to finish; the with block calls it for you —

A future (class Future) is an object that stands for a result that does not exist yet. future.result() waits for the task and returns its value. If the task raised an exception, result() raises the same exception in your thread. as_completed(futures) yields the futures in the order they finish.

from concurrent.futures import ThreadPoolExecutor, as_completed
PRICES = {"P001": 79.99, "P002": 249.00, "P003": 1299.00}
def fetch_price(product_id: str, delay: float) -> tuple[str, float]:
time.sleep(delay) # a simulated API call
return product_id, PRICES[product_id] # KeyError for an unknown id
jobs = [("P001", 0.3), ("P002", 0.1), ("P003", 0.2), ("P999", 0.05)]
with ThreadPoolExecutor(max_workers=4) as pool:
futures = {pool.submit(fetch_price, pid, delay): pid for pid, delay in jobs}
for future in as_completed(futures):
try:
product_id, price = future.result()
print(f"{product_id}: {price:.2f}")
except KeyError as error:
print(f"{futures[future]}: failed with KeyError {error}")
Output
P999: failed with KeyError 'P999'
P002: 249.00
P003: 1299.00
P001: 79.99

The results arrive in finish order: the shortest wait first. The failed task did not crash the program. Its KeyError waited inside its future until result() raised it. A dict from future to input lets you report which input failed.

The finish order depends on timing. When the order of your output matters, use pool.map(), or sort the results after as_completed().

The default number of workers is min(32, cores + 4) for threads and the number of cores for processes. Set max_workers yourself when a server limits how many requests you may send at once.

A process pool must start new Python processes and send them your function and data. Python sends them with pickle (module 07): it turns objects into bytes and back. So:

  • The function must be defined at the top level of a module, so that a worker can import it by name. A lambda or a function defined inside another function cannot be pickled.
  • Arguments and return values must be picklable, and they are copied. Sending a 1 GB DataFrame to each worker costs more than it saves.
  • On macOS and Windows, a new process spawns: it starts a fresh interpreter and imports your script as a module. Without the main guard if __name__ == "__main__":, each worker would run the top-level code of your script again, including the code that starts the pool. Python stops this with a RuntimeError.

The default start method (the way a new process is created) is spawn. Every pool script needs the main guard.

A pool script therefore runs as a real file, not in a REPL or on this page. This script computes, for each of the 4 sensors in data/sensors.csv, the highest mean of 6 consecutive valid readings (about one hour). Each sensor is one task:

pool_basics.py
# pool_basics.py: one task per sensor in a pool of worker processes.
import csv
import multiprocessing
from collections import defaultdict
from concurrent.futures import ProcessPoolExecutor
def load_temperatures(path: str) -> dict[str, list[float]]:
"""Temperatures per sensor, in time order, without blank readings."""
by_sensor: dict[str, list[float]] = defaultdict(list)
with open(path, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
if row["temperature_c"]:
by_sensor[row["sensor_id"]].append(float(row["temperature_c"]))
return dict(sorted(by_sensor.items()))
def max_hourly_mean(temperatures: list[float]) -> float:
"""Highest mean of 6 consecutive valid readings (about one hour)."""
window = 6
best = max(
sum(temperatures[i : i + window]) / window
for i in range(len(temperatures) - window + 1)
)
return round(best, 2)
def main() -> None:
data = load_temperatures("data/sensors.csv")
spawn = multiprocessing.get_context("spawn") # the same start method everywhere
with ProcessPoolExecutor(max_workers=4, mp_context=spawn) as pool:
results = list(pool.map(max_hourly_mean, data.values())) # input order
for sensor, value in zip(data, results, strict=True):
print(f"{sensor}: highest hourly mean {value} °C")
with spawn.Pool(processes=4) as pool: # the older multiprocessing API
old_api = pool.map(max_hourly_mean, data.values())
print("multiprocessing.Pool agrees:", old_api == results)
if __name__ == "__main__":
main()
Output
S1: highest hourly mean 26.6 °C
S2: highest hourly mean 30.53 °C
S3: highest hourly mean 27.96 °C
S4: highest hourly mean 31.22 °C
multiprocessing.Pool agrees: True

The script asks for the spawn start method by name, so it behaves the same on every operating system. multiprocessing.Pool is the older interface. It does the same job; concurrent.futures is the modern one and lets you swap processes for threads by changing one name.

asyncio runs many I/O-bound tasks in a single thread. The tasks cooperate: each one runs until it must wait, then hands control back. The keywords:

  • async def defines a coroutine function. Calling it does not run its body. It returns a coroutine: an object that can run, pause and resume.
  • await x pauses the current coroutine until x is done. Meanwhile, other tasks run. You can await only inside an async def. An object that you can await is an awaitable: a coroutine, a task or a future.
  • The event loop is the scheduler. It runs one task until that task awaits, then switches to another task that is ready.
  • asyncio.run(main()) creates an event loop, runs the coroutine main() to the end and closes the loop. Call it once, at the top of the program.
  • asyncio.gather(c1, c2, ...) runs several awaitables concurrently and returns their results as a list, in the order of the arguments.
import asyncio
async def fetch_page(page: int, delay: float) -> str:
print(f"start page {page}")
await asyncio.sleep(delay) # a simulated network wait; other tasks run now
print(f"done page {page}")
return f"page {page}"
async def main() -> list[str]:
return await asyncio.gather(
fetch_page(1, 0.3), fetch_page(2, 0.1), fetch_page(3, 0.2)
)
results = asyncio.run(main())
print(results)
Output
start page 1
start page 2
start page 3
done page 2
done page 3
done page 1
['page 1', 'page 2', 'page 3']

All three requests start at once. They finish in order of their delays, but gather returns the results in the order of its arguments. The whole run takes about 0.3 seconds, the longest delay, not 0.6.

sequenceDiagram
    participant L as Event loop
    participant A as fetch_page(1)
    participant B as fetch_page(2)
    L->>A: run until await
    A-->>L: waiting 0.3 s
    L->>B: run until await
    B-->>L: waiting 0.1 s
    Note over L: nothing to run, sleep
    L->>B: 0.1 s passed, resume
    B-->>L: done, "page 2"
    L->>A: 0.3 s passed, resume
    A-->>L: done, "page 1"

Calling a coroutine function without await is a common mistake. It returns a coroutine object and runs nothing:

coro = fetch_page(1, 0.1)
print(type(coro).__name__)
coro.close() # it never ran; close it to avoid a "never awaited" warning
Output
coroutine

Three more tools appear in the examples and the cheat sheet:

  • asyncio.Semaphore(n) lets at most n tasks into a block at a time: async with semaphore:. A semaphore is a counter-based lock. Use it to respect a server’s limit on parallel requests.
  • asyncio.TaskGroup (Python 3.11+) starts tasks with tg.create_task(...) and cancels the others if one fails.
  • asyncio.to_thread(func, *args) runs a normal blocking function in a thread, so it does not block the event loop.

Example 1 — Validate product IDs against a large catalog

Section titled “Example 1 — Validate product IDs against a large catalog”

Goal: A marketplace receives batches of 1,000 product IDs from sellers. Each ID must exist in a catalog of 100,000 products. Find out why the check is slow with a list and how much a set helps.

Step 1 — Build the catalog and one batch

Section titled “Step 1 — Build the catalog and one batch”
import random
import timeit
catalog_list = [f"P{n:06d}" for n in range(1, 100_001)]
catalog_set = set(catalog_list)
rng = random.Random(42)
batch = [f"P{rng.randrange(1, 120_001):06d}" for _ in range(1_000)]
print(len(catalog_list), catalog_list[0], catalog_list[-1])
print(batch[:4])
Output
100000 P000001 P100000
['P083811', 'P014593', 'P003279', 'P097197']

The catalog IDs run from P000001 to P100000. The batch draws numbers up to 120,000, so about one ID in six is unknown. A seeded random.Random(42) makes the batch the same on every run.

Step 2 — Count the comparisons of each lookup

Section titled “Step 2 — Count the comparisons of each lookup”
def list_comparisons(catalog: list[str], product_id: str) -> int:
"""How many items `product_id in catalog` compares before it stops."""
for position, item in enumerate(catalog, start=1):
if item == product_id:
return position
return len(catalog) # not found: every item was compared
known = sum(pid in catalog_set for pid in batch)
list_steps = sum(list_comparisons(catalog_list, pid) for pid in batch)
print("Known IDs:", known, "of", len(batch))
print(f"List: {list_steps:,} comparisons")
print(f"Set: about {len(batch):,} hash lookups")
Output
Known IDs: 834 of 1000
List: 58,350,701 comparisons
Set: about 1,000 hash lookups

The in operator on a list compares items from the start until it finds a match. A known ID costs on average half the catalog, an unknown ID costs the whole catalog. The set hashes the ID and jumps to its slot: about one step per lookup, whatever the size of the catalog. sum() over booleans counts the True values.

list_s = timeit.timeit(lambda: [pid in catalog_list for pid in batch], number=1)
set_s = timeit.timeit(lambda: [pid in catalog_set for pid in batch], number=100) / 100
print(f"list: {list_s * 1000:.1f} ms per batch")
print(f"set: {set_s * 1000:.3f} ms per batch")
print("set is faster:", set_s < list_s)
print("at least 100x faster:", list_s / set_s > 100)
Output
list: 310.6 ms per batch
set: 0.022 ms per batch
set is faster: True
at least 100x faster: True

The timings confirm the counts. The set version is so fast that one run is too short to measure well, so it runs 100 times and divides. The list version is slow enough to measure once.

Step 4 — Include the cost of building the set

Section titled “Step 4 — Include the cost of building the set”
build_s = timeit.timeit(lambda: set(catalog_list), number=10) / 10
print(f"build the set once: {build_s * 1000:.1f} ms")
print("build + set lookups beat list lookups:", build_s + set_s < list_s)
Output
build the set once: 2.0 ms
build + set lookups beat list lookups: True

Building the set is O(n)O(n): it touches all 100,000 IDs once. Even with this cost, the set wins on the very first batch. From the second batch on, the set is free: build it once, outside the loop, and reuse it.

Common mistakes:

  • Building the set inside the loop: if pid in set(catalog_list):. This costs O(n)O(n) per lookup, slower than the list.
  • Testing membership in a pandas column with in. "P000001" in df["product_id"] checks the index (0, 1, 2, …), not the values, and returns False. Use df["product_id"].isin(batch) for many IDs, or set(df["product_id"]).
  • Timing the fast version once. A run of a few microseconds is mostly noise; use number= and divide.

Example 2 — Count the comparisons of two sorting algorithms

Section titled “Example 2 — Count the comparisons of two sorting algorithms”

Goal: A dashboard sorts order lines by revenue. Show with exact counts that the built-in sorted() grows like nlog⁡nn \log n and a hand-written insertion sort grows like n2n^2.

Step 1 — Count comparisons with a key wrapper

Section titled “Step 1 — Count comparisons with a key wrapper”
from functools import cmp_to_key
comparisons = 0
def compare(a: float, b: float) -> int:
"""Compare two revenues like < does, and count the call."""
global comparisons
comparisons += 1
return (a > b) - (a < b) # -1, 0 or 1
comparisons = 0
print(sorted([66.49, 14.99, 249.0, 79.99], key=cmp_to_key(compare)))
print("Comparisons:", comparisons)
Output
[14.99, 66.49, 79.99, 249.0]
Comparisons: 7

functools.cmp_to_key turns a comparison function into a key, so sorted() calls compare for every comparison it makes. (a > b) - (a < b) is a compact way to get -1, 0 or 1, because True counts as 1.

Step 2 — Write insertion sort with the same counter

Section titled “Step 2 — Write insertion sort with the same counter”
def insertion_sort(values: list[float]) -> list[float]:
"""Sort a copy: insert each value into the sorted part on its left."""
result = list(values)
for i in range(1, len(result)):
current = result[i]
j = i - 1
while j >= 0 and compare(result[j], current) > 0:
result[j + 1] = result[j] # shift the larger value one step right
j -= 1
result[j + 1] = current
return result
comparisons = 0
print(insertion_sort([66.49, 14.99, 249.0, 79.99]))
print("Comparisons:", comparisons)
Output
[14.99, 66.49, 79.99, 249.0]
Comparisons: 4

Insertion sort takes each value and moves it left past every larger value. On random data, each value passes about half of the values before it, so the total is about n2/4n^2 / 4 comparisons. On 4 values, insertion sort even needs fewer comparisons than sorted(). Big-O speaks about large n.

Step 3 — Compare the counts as n doubles

Section titled “Step 3 — Compare the counts as n doubles”
import math
print(f"{'n':>5} {'insertion':>10} {'sorted()':>9} {'n log2 n':>9}")
for n in (250, 500, 1_000, 2_000):
sample = revenues[:n] # real revenues from data/sales.csv, in file order
comparisons = 0
insertion_sort(sample)
slow = comparisons
comparisons = 0
fast_result = sorted(sample, key=cmp_to_key(compare))
fast = comparisons
assert fast_result == sorted(sample)
print(f"{n:>5} {slow:>10,} {fast:>9,} {n * math.log2(n):>9,.0f}")
Output
n insertion sorted() n log2 n
250 14,188 1,656 1,991
500 60,368 3,833 4,483
1000 258,168 8,584 9,966
2000 986,856 18,903 21,932

Each time n doubles, insertion sort needs about 4 times more comparisons: quadratic growth. sorted() needs a little more than twice as many: nlog⁡nn \log n growth. Its counts stay a little below nlog⁡2nn \log_2 n. That formula gives only the growth rate. The true minimum for any sort that compares values is log⁡2(n!)≈nlog⁡2n−1.44 n\log_2(n!) \approx n \log_2 n - 1.44\,n comparisons, and the counts of sorted() are close to it. Python’s sort is a merge-based algorithm, and on data that is already partly in order it needs even fewer comparisons.

Step 4 — Check that the counts predict the time

Section titled “Step 4 — Check that the counts predict the time”
from functools import partial
sort_1000 = partial(insertion_sort, revenues[:1_000])
sort_2000 = partial(insertion_sort, revenues[:2_000])
t_1000 = min(timeit.repeat(sort_1000, number=1, repeat=3))
t_2000 = min(timeit.repeat(sort_2000, number=1, repeat=3))
print(f"insertion sort, 1,000 values: {t_1000 * 1000:.0f} ms")
print(f"insertion sort, 2,000 values: {t_2000 * 1000:.0f} ms")
print("about 4x slower:", 2.5 < t_2000 / t_1000 < 6)
Output
insertion sort, 1,000 values: 21 ms
insertion sort, 2,000 values: 82 ms
about 4x slower: True

Twice the data, about four times the time. functools.partial builds a function with no arguments for timeit; a lambda would do the same.

Common mistakes:

  • Writing your own sort. sorted() and list.sort() are O(nlog⁡n)O(n \log n), stable and written in C. Use key= to sort by any field.
  • Sorting inside a loop to get the current maximum. Sort once, or use max() (O(n)O(n)) or heapq for the top k.
  • Judging an algorithm on 20 items. At small n, the O(n2)O(n^2) version can even win. Test at the size you will run.

Example 3 — Profile and fix a slow monthly profit report

Section titled “Example 3 — Profile and fix a slow monthly profit report”

Goal: A finance script computes the gross profit per month from data/sales.csv and the unit costs in data/products.csv. It feels slow. Find the hotspot with cProfile, fix it and prove that the result did not change.

import cProfile
import csv
import pstats
import time
from collections import defaultdict
from datetime import datetime
def load_products(path: str) -> list[dict[str, str]]:
with open(path, newline="", encoding="utf-8") as f:
return list(csv.DictReader(f))
def month_of(text: str) -> str:
return datetime.strptime(text, "%Y-%m-%d").strftime("%Y-%m")
def find_cost(products: list[dict[str, str]], product_id: str) -> float:
for product in products:
if product["product_id"] == product_id:
return float(product["unit_cost"])
raise KeyError(product_id)
def monthly_profit(sales_path: str, products_path: str) -> dict[str, float]:
products = load_products(products_path)
totals: dict[str, float] = defaultdict(float)
with open(sales_path, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
cost = find_cost(products, row["product_id"]) * int(row["quantity"])
totals[month_of(row["order_date"])] += float(row["revenue"]) - cost
return dict(totals)
start = time.perf_counter()
slow = monthly_profit("data/sales.csv", "data/products.csv")
slow_s = time.perf_counter() - start
print(len(slow), "months; 2024-12 profit:", round(slow["2024-12"], 2))
print(f"Time: {slow_s:.3f} s")
Output
24 months; 2024-12 profit: 141714.37
Time: 0.100 s

The report is correct: 24 months, from 2023-01 to 2024-12. A tenth of a second sounds fine, but 10 years of data from 200 stores means about 80 times more lines: about 8 seconds, and every slow step grows with it.

with cProfile.Profile() as profiler:
monthly_profit("data/sales.csv", "data/products.csv")
profile = pstats.Stats(profiler).get_stats_profile()
mine = {"monthly_profit", "month_of", "find_cost", "load_products"}
rows = [(name, fp) for name, fp in profile.func_profiles.items() if name in mine]
rows.sort(key=lambda item: item[1].cumtime, reverse=True) # sort by cumulative
print(f"{'function':<16}{'ncalls':>8}")
for name, fp in rows:
print(f"{name:<16}{fp.ncalls:>8}")
Output
function ncalls
monthly_profit 1
month_of 20228
find_cost 20228
load_products 1

get_stats_profile() returns the profile as an object, so code can filter it. This page keeps only your own four functions and their call counts, because counts do not change between runs. Sorted by cumulative time, month_of comes right after the entry point: the date parsing costs more than the cost lookup. On your machine, pstats.Stats(profiler).sort_stats("cumulative").print_stats(10) shows the full table with times, as in the sample profile: strptime and its helpers in _strptime.py fill the top lines.

def load_costs(path: str) -> dict[str, float]:
with open(path, newline="", encoding="utf-8") as f:
return {row["product_id"]: float(row["unit_cost"]) for row in csv.DictReader(f)}
def monthly_profit_fast(sales_path: str, products_path: str) -> dict[str, float]:
costs = load_costs(products_path) # dict index: O(1) per lookup
totals: dict[str, float] = defaultdict(float)
with open(sales_path, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
cost = costs[row["product_id"]] * int(row["quantity"])
totals[row["order_date"][:7]] += float(row["revenue"]) - cost # "2024-12"
return dict(totals)
fast = monthly_profit_fast("data/sales.csv", "data/products.csv")
print("Same result:", fast == slow)
Output
Same result: True

Two changes. The dates are ISO strings (2024-12-05), so the month is simply the first 7 characters: no parsing at all. And the cost lookup uses a dict built once, instead of a scan of 30 products for every line. The additions happen in the same order with the same values, so even the float totals are identical.

inputs = ("data/sales.csv", "data/products.csv")
slow_s = min(timeit.repeat(lambda: monthly_profit(*inputs), number=1, repeat=3))
fast_s = min(timeit.repeat(lambda: monthly_profit_fast(*inputs), number=1, repeat=3))
print(f"slow: {slow_s * 1000:.0f} ms")
print(f"fast: {fast_s * 1000:.0f} ms")
print("at least 2x faster:", slow_s / fast_s >= 2)
Output
slow: 94 ms
fast: 27 ms
at least 2x faster: True

What remains is mostly csv.DictReader itself. To go much faster, you would change the tool: pd.read_csv or Polars parse the file in C (modules 24 and 31).

Common mistakes:

  • Optimizing before profiling. Here a rewrite of the cost lookup alone would have missed the bigger cost.
  • Reading absolute times from the profile. The profiler adds overhead to every call, so functions with many small calls look slower than they are. Find the hotspot with the profile; measure the fix with timeit.
  • Assuming that a date must be parsed. When the text is ISO and you need only the month, slicing is enough. Parse when you need real date arithmetic.

Example 4 — Replace a nested-loop join with a dict index

Section titled “Example 4 — Replace a nested-loop join with a dict index”

Goal: Marketing wants the revenue per contract type (month-to-month, one-year, two-year). The contract is in data/customers.csv (5,000 rows), the revenue in data/sales.csv (20,228 rows). Join them without a quadratic loop.

with open("data/customers.csv", newline="", encoding="utf-8") as f:
customers = list(csv.DictReader(f))
with open("data/sales.csv", newline="", encoding="utf-8") as f:
sales = list(csv.DictReader(f))
print(len(customers), "customers,", len(sales), "sales lines")
print(customers[0]["customer_id"], customers[0]["contract"])
Output
5000 customers, 20228 sales lines
C00001 two-year

Both tables are lists of dicts, one dict per row.

Step 2 — Join with a nested loop and count the work

Section titled “Step 2 — Join with a nested loop and count the work”
def nested_join(lines: list[dict[str, str]]) -> tuple[dict[str, float], int]:
totals: dict[str, float] = defaultdict(float)
steps = 0
for line in lines:
for customer in customers: # scan until the customer is found
steps += 1
if customer["customer_id"] == line["customer_id"]:
totals[customer["contract"]] += float(line["revenue"])
break
return dict(totals), steps
start = time.perf_counter()
nested_totals, steps = nested_join(sales[:2_000])
nested_s = time.perf_counter() - start
print(f"2,000 lines: {steps:,} comparisons in {nested_s:.2f} s")
# Count the comparisons of the full join without running it:
# a customer at position k in the list costs k comparisons.
position = {c["customer_id"]: k for k, c in enumerate(customers, start=1)}
full_steps = sum(position[line["customer_id"]] for line in sales)
print(f"All {len(sales):,} lines: {full_steps:,} comparisons")
Output
2,000 lines: 2,094,819 comparisons in 0.08 s
All 20,228 lines: 35,500,710 comparisons

Each line scans the customer list until it finds its customer. The cost is O(n⋅m)O(n \cdot m) for n sales lines and m customers. The first 2,000 lines are orders from early 2023, mostly by older customers near the front of the list, so they cost about 1,000 comparisons each. Later orders come from newer customers further back. The full join would need about 17 times the work of the sample, so this step runs only the sample.

Step 3 — Build a dict index and join in one pass

Section titled “Step 3 — Build a dict index and join in one pass”
start = time.perf_counter()
contract_of = {c["customer_id"]: c["contract"] for c in customers} # O(m), once
revenue_by_contract: dict[str, float] = defaultdict(float)
for line in sales: # O(n), one lookup per line
revenue_by_contract[contract_of[line["customer_id"]]] += float(line["revenue"])
dict_s = time.perf_counter() - start
for contract, revenue in sorted(revenue_by_contract.items()):
print(f"{contract:<15} {revenue:>13,.2f}")
print(f"All {len(sales):,} lines in {dict_s:.3f} s")
Output
month-to-month 1,493,913.37
one-year 1,179,430.27
two-year 923,180.19
All 20,228 lines in 0.004 s

The dict is the index: one pass over the customers to build it, then one O(1)O(1) lookup per sales line. The total cost is O(n+m)O(n + m): about 25,000 steps instead of 35 million.

dict_first: dict[str, float] = defaultdict(float)
for line in sales[:2_000]:
dict_first[contract_of[line["customer_id"]]] += float(line["revenue"])
print("Same totals on 2,000 lines:", dict(dict_first) == nested_totals)
print("Dict join is faster on 10x the data:", dict_s < nested_s)
Output
Same totals on 2,000 lines: True
Dict join is faster on 10x the data: True

The fast join gives the same totals on the same lines. And it processes all 20,228 lines in less time than the slow join needs for 2,000.

Common mistakes:

  • Building the index inside the loop. The index must be built once, before the loop.
  • Joining on a key that is not unique. A dict keeps only the last row for each key. Check len(contract_of) == len(customers) first.
  • Hand-writing joins at all in analysis code. pandas.merge and DuckDB use hash joins; SQLite uses an index. All of them avoid the full nested scan (module 25, module 30). Write the dict version in plain-Python tools and scripts.

Example 5 — Read report files from a slow network drive with threads

Section titled “Example 5 — Read report files from a slow network drive with threads”

Goal: The six monthly report files data/reports/2024-01.csv to 2024-06.csv live on a network drive. Each read waits about 0.25 seconds for the network before the data arrives. Read them concurrently with a thread pool.

Step 1 — Write the reader with a simulated delay

Section titled “Step 1 — Write the reader with a simulated delay”
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
NETWORK_DELAY = 0.25 # seconds of waiting per file, like a remote drive
def read_report(path: Path) -> tuple[str, float]:
"""Return the month and the revenue total of one report file."""
time.sleep(NETWORK_DELAY) # the thread waits here and releases the GIL
with path.open(newline="", encoding="utf-8") as f:
total = sum(float(row["revenue"]) for row in csv.DictReader(f))
return path.stem, round(total, 2)
paths = sorted(Path("data/reports").glob("2024-*.csv"))
start = time.perf_counter()
print(read_report(paths[0]))
print(f"One file: {time.perf_counter() - start:.2f} s")
Output
('2024-01', 14162.33)
One file: 0.26 s

time.sleep() stands in for the network. The parsing itself takes about a millisecond: this function is I/O-bound. path.stem is the file name without its suffix.

Step 2 — Read the files one after another

Section titled “Step 2 — Read the files one after another”
start = time.perf_counter()
sequential = [read_report(path) for path in paths]
seq_s = time.perf_counter() - start
print(sequential[:2])
print(f"Sequential: {seq_s:.2f} s for {len(paths)} files")
Output
[('2024-01', 14162.33), ('2024-02', 4719.04)]
Sequential: 1.54 s for 6 files

Six waits of 0.25 seconds in a row: about 1.5 seconds.

start = time.perf_counter()
with ThreadPoolExecutor(max_workers=6) as pool:
threaded = list(pool.map(read_report, paths))
thr_s = time.perf_counter() - start
print("Same results, same order:", threaded == sequential)
print(f"Threads: {thr_s:.2f} s")
print("at least 3x faster:", seq_s / thr_s > 3)
Output
Same results, same order: True
Threads: 0.26 s
at least 3x faster: True

The six waits overlap, so the total is about one wait. pool.map() returns the results in the order of paths, whatever the finish order, so the result equals the sequential list.

wanted = [*paths, Path("data/reports/2024-07.csv")] # July is not there yet
results: list[tuple[str, float]] = []
errors: list[str] = []
with ThreadPoolExecutor(max_workers=7) as pool:
futures = {pool.submit(read_report, path): path for path in wanted}
for future in as_completed(futures):
try:
results.append(future.result())
except FileNotFoundError:
errors.append(futures[future].name)
for month, total in sorted(results):
print(f"{month}: {total:>10,.2f}")
print("Missing:", errors)
print(f"Total: {sum(total for _, total in results):,.2f}")
Output
2024-01: 14,162.33
2024-02: 4,719.04
2024-03: 12,296.72
2024-04: 10,879.04
2024-05: 6,675.86
2024-06: 8,533.40
Missing: ['2024-07.csv']
Total: 57,266.39

With submit() and as_completed(), each failure stays in its own future. The loop collects the good results and the errors, and sorted() restores the month order, because as_completed yields in finish order.

Common mistakes:

  • Using pool.map() when a task can fail. map raises the first exception when you reach that result, and you lose the results after it. Use submit and handle each future.
  • Too many workers. A server or a network drive that allows 4 parallel connections gets slower, or blocks you, with 100 threads.
  • Updating a shared list or counter from many threads without a lock. Return results from the tasks instead.

Example 6 — Bootstrap confidence intervals in parallel with processes

Section titled “Example 6 — Bootstrap confidence intervals in parallel with processes”

Goal: For each product category, estimate a 95% confidence interval of the mean line revenue with a bootstrap (module 09): resample the lines with replacement 2,000 times and look at the spread of the resampled means (module 29 explains the statistics). The work is pure Python and CPU-bound. Compare one process, threads and a process pool.

import random
import statistics
electronics = [float(r["revenue"]) for r in sales if r["category"] == "Electronics"]
def bootstrap_ci(values: list[float], resamples: int = 2_000) -> tuple[float, float]:
rng = random.Random(42)
n = len(values)
means = sorted(sum(rng.choices(values, k=n)) / n for _ in range(resamples))
return means[int(0.025 * resamples)], means[int(0.975 * resamples) - 1]
start = time.perf_counter()
low, high = bootstrap_ci(electronics)
mean = statistics.fmean(electronics)
print(f"Electronics: mean {mean:.2f}, CI {low:.2f} to {high:.2f}")
print(f"One category: {time.perf_counter() - start:.2f} s")
Output
Electronics: mean 458.68, CI 440.62 to 476.99
One category: 0.26 s

rng.choices(values, k=n) draws n values with replacement. After sorting the 2,000 means, the values at positions 2.5% and 97.5% bound the interval. The function only computes: no waiting at all.

The process pool needs a real script with the main guard:

bootstrap_parallel.py
# bootstrap_parallel.py: bootstrap confidence intervals per category, three ways.
import csv
import random
import statistics
import time
from collections import defaultdict
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
RESAMPLES = 2_000
def load_revenue(path: str) -> dict[str, list[float]]:
"""Group the revenue of each sales line by product category."""
by_category: dict[str, list[float]] = defaultdict(list)
with open(path, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
by_category[row["category"]].append(float(row["revenue"]))
return dict(sorted(by_category.items()))
def bootstrap_ci(values: list[float]) -> tuple[float, float]:
"""95% bootstrap confidence interval of the mean. Pure Python, CPU-bound."""
rng = random.Random(42) # the same seed in every process: same result
n = len(values)
means = sorted(sum(rng.choices(values, k=n)) / n for _ in range(RESAMPLES))
return means[int(0.025 * RESAMPLES)], means[int(0.975 * RESAMPLES) - 1]
def main() -> None:
data = load_revenue("data/sales.csv")
groups = list(data.values())
start = time.perf_counter()
sequential = [bootstrap_ci(values) for values in groups]
t_seq = time.perf_counter() - start
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=6) as pool:
threaded = list(pool.map(bootstrap_ci, groups))
t_thr = time.perf_counter() - start
start = time.perf_counter()
with ProcessPoolExecutor(max_workers=6) as pool:
parallel = list(pool.map(bootstrap_ci, groups))
t_proc = time.perf_counter() - start
for (category, values), (low, high) in zip(data.items(), parallel, strict=True):
mean = statistics.fmean(values)
print(f"{category:<12} mean {mean:7.2f} 95% CI {low:7.2f} to {high:7.2f}")
print("Same results:", sequential == threaded == parallel)
print("Threads no faster than sequential:", t_thr > 0.7 * t_seq)
print("Processes faster than threads:", t_proc < 0.8 * t_thr)
print(f"Sequential: {t_seq:.2f} s")
print(f"Threads: {t_thr:.2f} s")
print(f"Processes: {t_proc:.2f} s")
if __name__ == "__main__":
main()
Output
Beauty mean 48.38 95% CI 46.71 to 50.11
Books mean 41.65 95% CI 40.19 to 43.17
Clothing mean 78.40 95% CI 75.65 to 81.29
Electronics mean 458.68 95% CI 440.62 to 476.99
Home mean 205.91 95% CI 200.57 to 211.68
Sports mean 163.35 95% CI 158.14 to 168.51
Same results: True
Threads no faster than sequential: True
Processes faster than threads: True
Sequential: 1.31 s
Threads: 1.29 s
Processes: 0.43 s

Read the two checks and the three timings:

  • Threads take as long as the sequential loop: Threads no faster than sequential: True means they need more than 70% of its time. The GIL lets only one thread run Python code, so six threads take turns on one core.
  • Processes are faster: Processes faster than threads: True means they need less than 80% of the threads’ time, and on a multi-core laptop they need far less. Each process has its own interpreter and GIL, so the categories run on different cores. The gain is less than 6 times, because starting the workers and pickling the data costs time, and the run waits for the slowest task (Clothing and Electronics have the most lines).
  • Same results: True for all three, because each task seeds its own random.Random(42). Never rely on a shared global random state across processes.

Common mistakes:

  • Forgetting the main guard. On macOS and Windows, the workers then fail with a RuntimeError about the bootstrapping phase.
  • Defining the task as a lambda or inside main(). It cannot be pickled. Define it at the top level.
  • Sending tiny tasks to processes. A task of 1 ms costs more to send than to run. Give each worker a large chunk of work, or use chunksize= in pool.map().

Example 7 — Fetch sensor data with asyncio and a semaphore

Section titled “Example 7 — Fetch sensor data with asyncio and a semaphore”

Goal: An IoT platform serves one sensor-day of readings per request. You need 4 sensors × 14 days = 56 requests. The API allows at most 8 requests in flight at once. Use asyncio with a semaphore, and see what one blocking call does.

Step 1 — Build a fake API from the sensor file

Section titled “Step 1 — Build a fake API from the sensor file”
import asyncio
readings: dict[tuple[str, str], list[float]] = defaultdict(list)
with open("data/sensors.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
if row["temperature_c"]: # skip blank readings
day = row["timestamp"][:10]
readings[row["sensor_id"], day].append(float(row["temperature_c"]))
in_flight = 0
max_in_flight = 0
async def fetch_day(sensor: str, day: str) -> float:
"""Simulated API call: wait 50 ms, return the day's mean temperature."""
global in_flight, max_in_flight
in_flight += 1
max_in_flight = max(max_in_flight, in_flight)
await asyncio.sleep(0.05) # network latency
in_flight -= 1
return round(statistics.fmean(readings[sensor, day]), 2)
print(len(readings), "sensor-days")
print(asyncio.run(fetch_day("S3", "2024-05-01")))
Output
56 sensor-days
21.29

The dict maps (sensor, day) to the day’s readings. fetch_day waits 50 ms like a network call and counts how many calls are running at once. In one thread, in_flight += 1 is safe: asyncio switches tasks only at an await, never in the middle of a line.

requests = sorted(readings) # 56 (sensor, day) pairs in a fixed order
async def fetch_all() -> list[float]:
return await asyncio.gather(*(fetch_day(s, d) for s, d in requests))
max_in_flight = 0
start = time.perf_counter()
means = asyncio.run(fetch_all())
print(f"{len(means)} results in {time.perf_counter() - start:.2f} s")
print("Max in flight:", max_in_flight)
Output
56 results in 0.05 s
Max in flight: 56

All 56 waits overlap, so the run takes about one wait. But 56 requests in flight break the API’s limit of 8. A real server would answer with HTTP status 429, “Too Many Requests” (module 16).

Step 3 — Limit concurrency with a semaphore

Section titled “Step 3 — Limit concurrency with a semaphore”
async def fetch_limited(semaphore: asyncio.Semaphore, sensor: str, day: str) -> float:
async with semaphore: # wait here while 8 requests are in flight
return await fetch_day(sensor, day)
async def fetch_all_limited(limit: int) -> list[float]:
semaphore = asyncio.Semaphore(limit)
return await asyncio.gather(*(fetch_limited(semaphore, s, d) for s, d in requests))
max_in_flight = 0
start = time.perf_counter()
limited = asyncio.run(fetch_all_limited(8))
print(f"{len(limited)} results in {time.perf_counter() - start:.2f} s")
print("Max in flight:", max_in_flight)
print("Same results:", limited == means)
s3 = [m for (s, _), m in zip(requests, limited, strict=True) if s == "S3"]
print("S3 first and last day:", s3[0], s3[-1])
Output
56 results in 0.36 s
Max in flight: 8
Same results: True
S3 first and last day: 21.29 25.85

The semaphore starts with 8 permits. Each async with takes one and gives it back at the end of the block. Task 9 waits until a permit is free. So 56 requests run in 7 waves of 8: about 0.35 seconds. Create the semaphore inside the coroutine that asyncio.run() runs. A semaphore binds to the first event loop that waits on it, so a module-level semaphore fails when a program calls asyncio.run() a second time. The data shows the calibration drift of sensor S3: its daily mean rises from 21.29 °C to 25.85 °C in two weeks.

Step 4 — See what one blocking call does

Section titled “Step 4 — See what one blocking call does”
async def fetch_day_blocking(sensor: str, day: str) -> float:
time.sleep(0.05) # wrong: blocks the whole event loop
return round(statistics.fmean(readings[sensor, day]), 2)
async def fetch_some_blocking() -> list[float]:
return await asyncio.gather(*(fetch_day_blocking(s, d) for s, d in requests[:12]))
start = time.perf_counter()
asyncio.run(fetch_some_blocking())
blocked_s = time.perf_counter() - start
print(f"12 blocking requests: {blocked_s:.2f} s")
print("Ran one after another:", blocked_s > 0.55)
Output
12 blocking requests: 0.67 s
Ran one after another: True

time.sleep() never gives control back to the event loop, so the 12 requests run strictly one after another: 12 × 0.05 = 0.6 seconds. With await asyncio.sleep() they would take 0.05 seconds. In real code, the same happens when you call requests.get() inside a coroutine.

Common mistakes:

  • Calling a blocking library (requests, time.sleep, a slow pandas step) inside async def. Use an async library such as httpx.AsyncClient, or await asyncio.to_thread(func, ...).
  • Calling asyncio.run() inside a running event loop, for example in a Jupyter notebook, which already runs one. There, write await main() directly.
  • Forgetting await. fetch_day("S1", "2024-05-01") alone creates a coroutine and runs nothing.
Mistake Symptom Fix
Optimizing without measuring A day of work, no speed-up Profile first; fix the top function of your own
x in big_list inside a loop Runtime grows with the square of the data Build set(big_list) once, before the loop
Nested loops to join two tables Script runs for minutes on 100,000 rows Build a dict index on one table
list.pop(0) for a queue Slows down as the queue grows collections.deque and popleft()
Timing fast code once with perf_counter Results jump from run to run timeit with number=; take the minimum of repeat()
time.time() for benchmarks Odd or negative durations time.perf_counter()
Trusting absolute times from cProfile Many small functions look slow Find the hotspot with the profile; time the fix with timeit
Threads for pure Python computation No speed-up, sometimes slower ProcessPoolExecutor or NumPy
Process pool without if __name__ == "__main__": RuntimeError about the bootstrapping phase in the workers, BrokenProcessPool in the parent (macOS, Windows) Put the pool code in main() behind the guard
A lambda as a process task PicklingError (or AttributeError: Can't get local object) Define the task at module level
Many tiny tasks in a process pool Slower than one process Fewer, bigger tasks; chunksize= in map()
Shared counter updated from threads Wrong totals, now and then threading.Lock, or return results instead
time.sleep() or requests.get() in a coroutine asyncio runs tasks one by one await asyncio.sleep(), httpx.AsyncClient, asyncio.to_thread
Calling a coroutine without await Nothing happens; “coroutine was never awaited” warning await coro, or asyncio.run(coro) at the top
Printing as_completed results directly Different order on every run Use pool.map(), or sort the results
Unlimited gather against an API HTTP 429 errors, blocked client asyncio.Semaphore(n) around each request
  • Web servers: FastAPI and other async frameworks run on an asyncio event loop, so one process serves thousands of waiting connections. A blocking call in a request handler slows every user at once.
  • Automation: a backup or deployment script copies 500 files to cloud storage with a ThreadPoolExecutor of 16 threads instead of one at a time.
  • Tooling: test runners such as pytest-xdist run test files in a pool of processes, and image or video converters process one file per core.
  • Debugging production: when an API endpoint gets slow, engineers attach a sampling profiler such as py-spy to the running server to see the hot functions without restarting it.
  • Measure, profile, fix the hotspot, test, measure again. Never optimize by guessing.
  • Big-O predicts how work grows: O(1)O(1) and O(log⁡n)O(\log n) scale to any size, O(nlog⁡n)O(n \log n) is the cost of a sort, O(n2)O(n^2) is a nested loop and breaks on big data.
  • time.perf_counter() measures wall-clock time; time.process_time() measures CPU time. A large gap means I/O-bound code.
  • timeit repeats code for stable micro-benchmarks. Divide by number; take the minimum of repeat().
  • cProfile records every call; pstats sorts by cumulative or tottime. Call counts are exact; times include profiler overhead.
  • Speed often comes from the data structure: sets and dicts for lookups, a dict index for joins, deque for queues, built-ins such as sum() instead of Python loops.
  • The GIL lets one thread at a time run Python code. Threads speed up waiting, processes speed up pure Python computing. Free-threaded builds (3.13+) remove the GIL, but they are optional.
  • ThreadPoolExecutor and ProcessPoolExecutor share one API: map() keeps input order, submit() + as_completed() yield in finish order and keep each error in its future.
  • Process pools need top-level functions, picklable data and the main guard.
  • asyncio runs many waiting tasks in one thread: async def, await, asyncio.run(), gather() (results in argument order) and Semaphore to limit concurrency. Never block the event loop.

Q1. A function takes 2 seconds on 10,000 rows. How long do you expect it to take on 100,000 rows if it is O(n)O(n)? If it is O(n2)O(n^2)?

Answer

About 20 seconds for O(n)O(n): ten times the data, ten times the work. About 200 seconds for O(n2)O(n^2): ten times the data, a hundred times the work.

Q2. Why is pid in catalog_set fast and pid in catalog_list slow on 100,000 IDs?

Answer

A set is a hash table. It hashes pid and checks one slot: O(1)O(1) on average. A list has no index by value, so in compares items from the start until it finds a match: O(n)O(n), up to 100,000 comparisons for one unknown ID.

Q3. Why does timeit run code many times, and which value of timeit.repeat() should you report?

Answer

One run of fast code is too short to measure well and is disturbed by other programs. Many runs make the total long enough to measure well. Report the minimum of repeat(): it is the run with the least disturbance. Divide it by number to get the time per call.

Q4. In a cProfile table, what is the difference between tottime and cumtime?

Answer

tottime is the time spent in the function’s own code. cumtime also includes the time of every function it calls. A function with a large cumtime and a small tottime delegates the slow work to a function it calls; look further down that call tree.

Q5. A script downloads 200 files and spends 95% of its time waiting for the network. Which tool do you choose, and why?

Answer

A ThreadPoolExecutor (or asyncio with an async HTTP client). The work is I/O-bound. A waiting thread releases the GIL, so the downloads overlap. Processes would also work, but they cost more to start and give no extra benefit for waiting.

Q6. Explain the GIL in two sentences. What does it mean for CPU-bound pure Python code in threads?

Answer

The GIL is a lock in CPython that a thread must hold to run Python code, so only one thread of a process runs Python code at a time. CPU-bound pure Python code in threads therefore takes turns on one core and does not get faster; use processes instead (or a free-threaded build of Python 3.13+).

Q7. Why must a ProcessPoolExecutor script use if __name__ == "__main__":, and why can the task not be a lambda?

Answer

With the spawn start method (the default on macOS and Windows), every worker imports your script as a module. Without the guard, each worker would run the code that starts the pool again; Python stops this with a RuntimeError. Tasks are sent to the workers with pickle, which stores a function by its module and name. A lambda has no importable name, so it cannot be pickled.

Q8. What is the difference between pool.map(func, items) and submit() with as_completed()?

Answer

map returns results in the order of items and raises the first exception when you reach that result. submit returns one future per task; as_completed yields the futures in the order they finish, and each future keeps its own result or exception. Use map for simple, ordered work and submit when you need per-task error handling or early results.

Q9. Inside an async def, a colleague calls time.sleep(1). What happens to the other tasks?

Answer

They all stop for 1 second. asyncio runs every task in one thread and switches only at an await. time.sleep() blocks the thread, so the event loop cannot switch. Use await asyncio.sleep(1).

Q10. What does asyncio.Semaphore(8) do in Example 7, and why is it needed?

Answer

It lets at most 8 tasks into the async with semaphore: block at a time. Task 9 waits until one of the 8 finishes. It keeps the client within the API’s limit of 8 parallel requests, so the server does not reject requests with HTTP 429.

Q11. In Example 7, gather() returns 56 means. Do they come in the order in which the requests finished?

Answer

No. asyncio.gather() returns results in the order of its arguments, whatever the finish order. That makes its output deterministic.

Your progress

0 / 4 done

  • Exercises: 26 exercises on big-O, timing, profiling, data structures, threads, processes and asyncio.
  • Mini-project: profile and speed up a nightly sales report, then run its slow steps concurrently.
  • Cheat sheet: big-O tables, timing and profiling commands, and the concurrency APIs on one page.
  • Next module: 16. APIs and web data calls real HTTP APIs with requests and httpx, handles pagination, rate limits and retries, and parses HTML.