Skip to content

Performance and concurrency

Fast Python comes from three habits: measure first, pick the right data structure, and use concurrency only for the kind of work it helps. This page gives the costs, the measuring tools and copy-ready templates for thread pools, process pools and asyncio.

I want to… Use… Example
time one run of a slow step time.perf_counter() start = perf_counter() … perf_counter() - start
benchmark a small snippet timeit.timeit(func, number=n) timeit(lambda: sum(xs), number=100) / 100
benchmark with less noise min(timeit.repeat(...)) the minimum, not the mean
benchmark from a terminal python -m timeit python -m timeit -s "xs = list(range(1000))" "sum(xs)"
find the slow function python -m cProfile -s cumulative script.py or with cProfile.Profile() as p:
measure memory tracemalloc tracemalloc.get_traced_memory()
test membership many times a set if pid in valid_ids:
look up records by key a dict index built once by_id = {r["id"]: r for r in rows}
a FIFO queue collections.deque q.append(x); q.popleft()
count values collections.Counter Counter(levels)
the top k items heapq.nlargest(k, xs) nlargest(10, orders, key=...)
search a sorted list bisect.bisect_left O(log⁡n)O(\log n)
avoid recomputation functools.cache @cache on a pure function
build a long string "".join(parts) not s += part in a loop
fast numeric loops NumPy vector operations (prices * qty).sum()
stream a big file a generator sum(1 for line in f if "ERROR" in line)
speed up many waits (network, disk) ThreadPoolExecutor pool.map(fetch, urls)
speed up pure Python computing ProcessPoolExecutor pool.map(simulate, seeds)
thousands of concurrent connections asyncio await asyncio.gather(*tasks)
results in input order pool.map / asyncio.gather
results as they finish as_completed for fut in as_completed(futures):
limit concurrency asyncio.Semaphore(n), max_workers=n async with sem:
a time limit asyncio.timeout(s), future.result(timeout=s) async with asyncio.timeout(5):
run blocking code from async code asyncio.to_thread await asyncio.to_thread(requests.get, url)
cancel the rest when one task fails asyncio.TaskGroup async with asyncio.TaskGroup() as tg:
share data between threads safely threading.Lock, queue.Queue with lock: total += x
check whether the GIL is on sys._is_gil_enabled() Python 3.13+
Operation Cost Note
lst[i], lst[i] = x, len(lst) O(1)O(1)
lst.append(x), lst.pop() O(1)O(1) amortized at the end
lst.insert(0, x), lst.pop(0) O(n)O(n) shifts every item: use deque
x in lst, lst.index(x), lst.count(x), lst.remove(x) O(n)O(n) a scan
lst[a:b], lst.copy(), lst + other O(k)O(k) / O(n)O(n) copies
lst.sort(), sorted(xs) O(nlog⁡n)O(n \log n) stable
min, max, sum, any, all O(n)O(n) one pass
d[k], d[k] = v, k in d, del d[k], d.get(k) O(1)O(1) average hashing
set.add, x in s, s.discard(x) O(1)O(1) average
a | b / a & b (sets of sizes n and m) O(n+m)O(n + m) / O(min⁡(n,m))O(\min(n, m))
deque.append, appendleft, pop, popleft O(1)O(1) both ends
deque[i] in the middle O(n)O(n)
heapq.heappush, heappop O(log⁡n)O(\log n)
heapq.nlargest(k, xs) O(nlog⁡k)O(n \log k)
bisect.bisect_left O(log⁡n)O(\log n) on a sorted list
bisect.insort O(n)O(n) the insert shifts items
s + t (strings), s.replace, x in s O(n)O(n) strings are immutable
"".join(parts) O(total length)O(\text{total length}) one copy
s += piece in a loop up to O(n2)O(n^2) many copies
n O(log⁡n)O(\log n) O(n)O(n) O(nlog⁡n)O(n \log n) O(n2)O(n^2)
1,000 10 1,000 10,000 1,000,000
1,000,000 20 1,000,000 20,000,000 101210^{12}

A rough guide: pure Python does about 10710^7 simple steps per second. O(n2)O(n^2) on a million items never finishes.

import timeit
ids = [f"C{i:05d}" for i in range(5_000)]
as_list, as_set = ids, set(ids)
probe = "C04999" # the worst case for a list: the last item
t_list = min(timeit.repeat(lambda: probe in as_list, number=200, repeat=3))
t_set = min(timeit.repeat(lambda: probe in as_set, number=200, repeat=3))
print(t_set < t_list, t_list / t_set > 10) # print comparisons, not raw timings
Output
True True
import cProfile
import pstats
def parse(lines: list[str]) -> list[float]:
return [float(x) for x in lines]
def pipeline() -> float:
return sum(sum(parse(["21.5", "22.0", "19.8"])) for _ in range(100))
with cProfile.Profile() as profiler:
pipeline()
stats = pstats.Stats(profiler).strip_dirs().sort_stats(pstats.SortKey.CUMULATIVE)
funcs = stats.get_stats_profile().func_profiles # name -> FunctionProfile
print(funcs["pipeline"].ncalls, funcs["parse"].ncalls) # call counts are exact
Output
1 100
import tracemalloc
tracemalloc.start()
squares_list = [n * n for n in range(100_000)] # stores every item
_, peak_list = tracemalloc.get_traced_memory()
del squares_list
tracemalloc.reset_peak() # start a new peak measurement
total = sum(n * n for n in range(100_000)) # a generator: one item at a time
_, peak_gen = tracemalloc.get_traced_memory()
tracemalloc.stop()
print(total, peak_gen < peak_list / 10)
Output
333328333350000 True
Terminal
python -m timeit -s "xs = list(range(10**5))" "sum(xs)" # -n loops, -r repeats
python -m cProfile -s cumulative report.py | head -25 # sorted profile
python -m cProfile -o report.prof report.py # save, then:
python -m pstats report.prof # interactive: sort, stats 10
python -X importtime -c "import pandas" 2> imports.txt # slow imports
Profile column Meaning
ncalls number of calls (3/1: 3 calls, 1 not recursive)
tottime time in the function itself
cumtime time in the function and everything it calls
percall tottime / ncalls, then cumtime / ncalls

Other tools: py-spy (a sampling profiler that attaches to a running process), line_profiler (time per line), scalene (CPU and memory), memray (memory).

Need Slow Fast Why
many membership tests x in a_list x in a_set O(n)O(n) → O(1)O(1)
join two record lists nested loops a dict index on one side O(n⋅m)O(n \cdot m) → O(n+m)O(n + m)
a queue lst.pop(0) deque.popleft() O(n)O(n) → O(1)O(1)
counts lst.count(x) per value Counter(lst) one pass
top k sorted(xs)[:k] heapq.nsmallest(k, xs) no full sort
a sorted list kept up to date append and sort each time bisect.insort no re-sort
the same slow call again recompute @cache a dict lookup
big text s += part "".join(parts) one copy
numeric arrays a Python loop NumPy / pandas vector operations (NumPy ufuncs) the loop runs in C
many small objects a dict per object @dataclass(slots=True) or tuples less memory
a huge file f.readlines() for line in f: constant memory
from collections import Counter
orders = [("O1", "C01", 79.99), ("O2", "C02", 14.99), ("O3", "C01", 249.0)]
customers = [("C01", "North"), ("C02", "West")]
region_of = dict(customers) # an index: built once in O(m)
revenue = Counter()
for _, customer_id, amount in orders: # O(n) lookups, no inner loop
revenue[region_of[customer_id]] += amount
print(dict(revenue))
Output
{'North': 328.99, 'West': 14.99}
threading / ThreadPoolExecutor multiprocessing / ProcessPoolExecutor asyncio
speeds up I/O-bound work: network, disk, sleeps CPU-bound pure Python many I/O tasks at once
runs Python in parallel no (GIL), yes on the free-threaded build yes no: one thread
memory shared separate; arguments are pickled shared
start cost small large tiny
typical count 4–32 about one per core thousands of tasks
switches tasks at any bytecode the OS only at await
main risk race conditions on shared data main guard, pickling, copying big data one blocking call stalls everything
libraries any (requests, database drivers) any picklable function async ones (httpx.AsyncClient, asyncpg)
Situation Choose
download 50 files or call an API 200 times threads, or asyncio with an async client
parse 1,000 files with pure Python processes
NumPy, pandas, scikit-learn heavy math vectorize first (NumPy); often already parallel inside C; try n_jobs=-1 before a pool
a web server with many idle connections asyncio (FastAPI, aiohttp)
a blocking library inside async code asyncio.to_thread
CPU work and you have the free-threaded build threads (check that your libraries support it)

The global interpreter lock (GIL) is a lock inside standard CPython that lets only one thread run Python bytecode at a time. Threads still help with I/O, because a thread that waits for the network, the disk or time.sleep releases the GIL, and many C libraries (NumPy, hashlib, zlib) release it during long computations. Pure Python computation in threads does not get faster. Each process has its own interpreter and its own GIL, so process pools run Python code in parallel at the price of pickling data between processes.

Python 3.13 added an optional free-threaded build without a GIL (the python3.13t executable). Python 3.14 made it officially supported, but it is still a separate download, not the default. On it, threads run Python code on several cores at once. Single-threaded code runs a little slower, and every C extension must declare support; otherwise the GIL turns back on when that extension loads. Check with sys._is_gil_enabled() (3.13+) and sysconfig.get_config_var("Py_GIL_DISABLED"). Python 3.14 also adds concurrent.futures.InterpreterPoolExecutor: several interpreters in one process, each with its own GIL.

import queue
import threading
total = 0
lock = threading.Lock()
def add_many(n: int) -> None:
global total
for _ in range(n):
with lock: # one thread at a time in this block
total += 1
threads = [threading.Thread(target=add_many, args=(10_000,)) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print(total) # always 40000 with the lock
tasks: queue.Queue[str | None] = queue.Queue()
results: queue.Queue[str] = queue.Queue() # thread-safe without a lock
def worker() -> None:
while (item := tasks.get()) is not None: # None is the stop signal
results.put(item.upper())
workers = [threading.Thread(target=worker) for _ in range(2)]
for w in workers:
w.start()
for item in ["s01", "s02", "s03"]:
tasks.put(item)
for _ in workers:
tasks.put(None) # one sentinel per worker
for w in workers:
w.join()
print(sorted(results.get() for _ in range(results.qsize())))
Output
40000
['S01', 'S02', 'S03']
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
def fetch(page: int) -> str:
time.sleep(0.02 * (4 - page)) # stands for a network call
if page == 3:
raise TimeoutError(f"page {page} timed out")
return f"page {page}: ok"
with ThreadPoolExecutor(max_workers=4) as pool: # 1) map: input order
print(list(pool.map(fetch, [1, 2])))
results, errors = {}, {}
with ThreadPoolExecutor(max_workers=4) as pool: # 2) submit: errors per task
futures = {pool.submit(fetch, p): p for p in [1, 2, 3, 4]}
for future in as_completed(futures): # finish order
page = futures[future]
try:
results[page] = future.result(timeout=5) # re-raises the task's error
except TimeoutError as err:
errors[page] = str(err)
print(sorted(results), errors)
Output
['page 1: ok', 'page 2: ok']
[1, 2, 4] {3: 'page 3 timed out'}
cpu_pool.py (run as a file)
import multiprocessing
from concurrent.futures import ProcessPoolExecutor
def simulate(seed: int) -> float: # top level: workers import it by name
import random
rng = random.Random(seed) # a seed per task: same result in any process
return sum(rng.random() for _ in range(1_000_000)) / 1_000_000
def main() -> None:
ctx = multiprocessing.get_context("spawn") # same behavior on every OS
with ProcessPoolExecutor(max_workers=4, mp_context=ctx) as pool:
means = list(pool.map(simulate, range(8), chunksize=2))
print(round(sum(means) / len(means), 3))
if __name__ == "__main__": # required: each worker imports this file
main()
API Does
ThreadPoolExecutor(max_workers=n) default min(32, cpu_count + 4) threads
ProcessPoolExecutor(max_workers=n, mp_context=ctx) default: one process per CPU
pool.map(func, items, timeout=None, chunksize=1) results in input order; the first error is raised while you iterate
pool.submit(func, *args, **kwargs) one task, returns a Future
future.result(timeout=s) the value, or the task’s exception
as_completed(futures, timeout=s) futures in finish order
wait(futures, return_when=FIRST_COMPLETED) (done, not_done) sets
pool.shutdown(cancel_futures=True) stop and drop queued tasks
import asyncio
async def fetch(day: str, delay: float, sem: asyncio.Semaphore) -> str:
async with sem: # at most 2 at a time
await asyncio.sleep(delay) # never time.sleep() in a coroutine
return f"{day}: ok"
async def main() -> None:
sem = asyncio.Semaphore(2) # create inside the running loop
days = ["2024-05-01", "2024-05-02", "2024-05-03"]
print(await asyncio.gather(*(fetch(d, 0.02, sem) for d in days))) # input order
results = await asyncio.gather( # errors as values instead of raising
fetch("ok", 0.01, sem), asyncio.wait_for(asyncio.sleep(1), timeout=0.01),
return_exceptions=True,
)
print([type(r).__name__ for r in results])
try:
async with asyncio.timeout(0.02): # a deadline for the whole block
await asyncio.sleep(1)
except TimeoutError:
print("timed out")
async with asyncio.TaskGroup() as tg: # waits for all; cancels on a failure
tasks = [tg.create_task(fetch(d, 0.01, sem)) for d in days[:2]]
print([t.result() for t in tasks])
total = await asyncio.to_thread(sum, range(1_000)) # blocking code in a thread
print(total)
asyncio.run(main()) # one entry point per program
Output
['2024-05-01: ok', '2024-05-02: ok', '2024-05-03: ok']
['str', 'TimeoutError']
timed out
['2024-05-01: ok', '2024-05-02: ok']
499500
import asyncio
async def producer(queue: asyncio.Queue[int]) -> None:
for n in range(5):
await queue.put(n)
async def consumer(queue: asyncio.Queue[int], out: list[int]) -> None:
while True:
n = await queue.get()
out.append(n * n)
queue.task_done()
async def pipeline() -> list[int]:
queue: asyncio.Queue[int] = asyncio.Queue(maxsize=2) # back-pressure
out: list[int] = []
workers = [asyncio.create_task(consumer(queue, out)) for _ in range(2)]
await producer(queue)
await queue.join() # wait until every item is processed
for w in workers:
w.cancel()
return sorted(out)
print(asyncio.run(pipeline()))
Output
[0, 1, 4, 9, 16]
API Does
async def f() f() returns a coroutine; nothing runs until it is awaited
await x pause this coroutine until x finishes
asyncio.run(main()) start a loop, run main, close the loop
asyncio.gather(*aws, return_exceptions=False) run together; results in argument order
asyncio.TaskGroup() structured tasks; cancels siblings on an error (3.11+)
asyncio.create_task(coro) start now; keep a reference
asyncio.Semaphore(n) a concurrency limit
asyncio.timeout(s), asyncio.wait_for(aw, s) deadlines; raise TimeoutError
asyncio.as_completed(aws) results in finish order
asyncio.to_thread(func, *args) run a blocking call in a thread
asyncio.Queue(maxsize=n) producer and consumer tasks
asyncio.sleep(s) a non-blocking wait

In Jupyter the loop is already running: write await main(), not asyncio.run(main()).

Trap Symptom Fix
optimizing without measuring effort spent on the wrong code profile first, then time the fix
one timing of fast code noise larger than the effect timeit with number=, the minimum of repeat
x in big_list inside a loop quadratic time build a set or dict once, outside the loop
s += piece in a loop slow on long strings "".join(parts)
threads for CPU-bound Python no speed-up, sometimes slower processes (or NumPy, or the free-threaded build)
shared counters in threads lost updates, wrong totals a Lock, or return results instead of sharing
a process pool without the main guard RuntimeError about the bootstrapping phase if __name__ == "__main__":
a lambda or nested function in a process pool PicklingError or AttributeError: Can't pickle local object a top-level function
many tiny tasks in a process pool slower than a plain loop few, large chunks; chunksize=
big arguments to processes time goes to pickling pass file paths or indexes, not data
as_completed order output order changes between runs sort, or use map
a coroutine called without await it never runs; RuntimeWarning: coroutine ... was never awaited await it or wrap it in a task
time.sleep or requests.get in a coroutine every task stalls asyncio.sleep, an async client or to_thread
a task without a reference it can be garbage collected mid-run keep the task, or use a TaskGroup
unlimited gather against a real API HTTP 429 rate limits, bans a Semaphore
asyncio.run inside Jupyter RuntimeError: asyncio.run() cannot be called from a running event loop await main()
a module-level asyncio.Semaphore or Queue errors when asyncio.run is called twice create them inside main()
assuming the free-threaded build is installed no speed-up from threads check sys._is_gil_enabled()