The essentials of module 15 on one page. Every runnable block on this page is checked against its output. Timings vary between machines, so the blocks print comparisons and counts, not durations.
I want to…
Use…
Example
time one run of a block
time.perf_counter() twice
start = time.perf_counter() … time.perf_counter() - start
measure CPU time only
time.process_time()
large wall time, small CPU time → I/O-bound
micro-benchmark a call
timeit.timeit(func, number=n) / n
timeit.timeit(lambda: sum(xs), number=100)
benchmark with less noise
min(timeit.repeat(..., repeat=5, number=n)) / n
take the minimum, not the mean
benchmark from the terminal
python -m timeit -s "setup" "stmt"
python -m timeit -s "xs = list(range(10**5))" "sum(xs)"
profile a whole script
python -m cProfile -s cumulative script.py
add -o out.prof to save the stats
profile one block
with cProfile.Profile() as profiler:
then pstats.Stats(profiler)
show the slowest call trees
stats.sort_stats("cumulative").print_stats(10)
"tottime" for the function’s own time
read profile data in code
stats.get_stats_profile().func_profiles[name]
.ncalls, .tottime, .cumtime
test membership many times
a set
pid in valid_ids
look up rows by key
a dict index, built once
by_id = {r["id"]: r for r in rows}
join two lists of records
a dict index on one side
O ( n + m ) O(n + m) O ( n + m ) instead of O ( n ⋅ m ) O(n \cdot m) O ( n ⋅ m )
use a queue (FIFO)
collections.deque
q.append(x), q.popleft()
keep the last N values
deque(maxlen=N)
rolling windows
count values
collections.Counter
Counter(categories).most_common(3)
get the top k
heapq.nlargest(k, items, key=...)
top 10 orders
search a sorted list
bisect.bisect_left(sorted_list, x)
O ( log n ) O(\log n) O ( log n )
cache an expensive pure function
@functools.cache
the same arguments → no second computation
speed up waiting (I/O)
ThreadPoolExecutor or asyncio
downloads, API calls, slow drives
speed up pure Python computing
ProcessPoolExecutor
bootstrap, simulations, parsing many files
run tasks and keep the input order
pool.map(func, items)
results in the order of items
handle each task’s error
pool.submit() + as_completed() + future.result()
errors stay in their future
run coroutines concurrently
await asyncio.gather(*coros)
results in argument order
limit concurrent requests
asyncio.Semaphore(n)
async with semaphore:
call blocking code from async code
await asyncio.to_thread(func, *args)
requests.get, file reads
give up after a time limit
async with asyncio.timeout(5):
Python 3.11+
check for the GIL
sys._is_gil_enabled()
Python 3.13+; True on the standard build
Big-O
Name
Steps at n = 1,000
Steps at n = 1,000,000
Typical code
O ( 1 ) O(1) O ( 1 )
constant
1
1
d[key], x in a_set, lst[i], lst.append(x)
O ( log n ) O(\log n) O ( log n )
logarithmic
10
20
bisect, heapq.heappush
O ( n ) O(n) O ( n )
linear
1,000
1,000,000
one loop, x in a_list, sum, max, Counter
O ( n log n ) O(n \log n) O ( n log n )
linearithmic
10,000
20,000,000
sorted, list.sort
O ( n 2 ) O(n^2) O ( n 2 )
quadratic
1,000,000
10 12 10^{12} 1 0 12
nested loops over the same data, x in list inside a loop
O ( 2 n ) O(2^n) O ( 2 n )
exponential
—
—
naive recursion such as Fibonacci without a cache
Rules of thumb: drop constants (O ( 2 n ) O(2n) O ( 2 n ) is O ( n ) O(n) O ( n ) ), keep the largest term (O ( n 2 + n ) O(n^2 + n) O ( n 2 + n ) is O ( n 2 ) O(n^2) O ( n 2 ) ), and two inputs keep two letters (O ( n ⋅ m ) O(n \cdot m) O ( n ⋅ m ) ).
Operation
list
dict
set
deque
x in c
O ( n ) O(n) O ( n )
O ( 1 ) O(1) O ( 1 ) (keys)
O ( 1 ) O(1) O ( 1 )
O ( n ) O(n) O ( n )
c[i] / c[key]
O ( 1 ) O(1) O ( 1 )
O ( 1 ) O(1) O ( 1 )
—
O ( n ) O(n) O ( n ) ; O ( 1 ) O(1) O ( 1 ) at the ends
append / add at the end
O ( 1 ) O(1) O ( 1 ) amortized
O ( 1 ) O(1) O ( 1 )
O ( 1 ) O(1) O ( 1 )
O ( 1 ) O(1) O ( 1 )
insert / remove at the front
O ( n ) O(n) O ( n )
—
—
O ( 1 ) O(1) O ( 1 )
pop() from the end
O ( 1 ) O(1) O ( 1 )
popitem() O ( 1 ) O(1) O ( 1 )
pop() O ( 1 ) O(1) O ( 1 )
O ( 1 ) O(1) O ( 1 )
remove a given value
O ( n ) O(n) O ( n )
del d[k] O ( 1 ) O(1) O ( 1 )
discard(x) O ( 1 ) O(1) O ( 1 )
O ( n ) O(n) O ( n )
min, max, sum
O ( n ) O(n) O ( n )
O ( n ) O(n) O ( n )
O ( n ) O(n) O ( n )
O ( n ) O(n) O ( n )
copy, list(c)
O ( n ) O(n) O ( n )
O ( n ) O(n) O ( n )
O ( n ) O(n) O ( n )
O ( n ) O(n) O ( n )
sort
O ( n log n ) O(n \log n) O ( n log n )
—
—
—
Module
Operation
Cost
heapq
heappush, heappop
O ( log n ) O(\log n) O ( log n )
heapq
nlargest(k, items)
O ( n log k ) O(n \log k) O ( n log k )
bisect
bisect_left, bisect_right
O ( log n ) O(\log n) O ( log n )
bisect
insort
O ( n ) O(n) O ( n ) : the search is fast, the insert moves items
str
"".join(parts)
O ( total length ) O(\text{total length}) O ( total length )
values = list ( range ( 100_000 ))
start = time.perf_counter() # wall-clock time, for one run of a slow block
elapsed = time.perf_counter() - start
per_call = timeit.timeit( lambda : sum (values), number = 100 ) / 100 # seconds per call
best = min (timeit.repeat( "sum(values)" , globals = globals (), repeat = 5 , number = 50 )) / 50
print (total, type (elapsed). __name__ , type (per_call). __name__ ) # seconds as floats
Tool
Measures
Use for
time.perf_counter()
wall-clock time, high resolution
one run of a slow step
time.process_time()
CPU time of this process
I/O-bound or CPU-bound?
time.time()
the system clock (can jump)
timestamps, not benchmarks
timeit.timeit(stmt, number=n)
total of n runs
micro-benchmarks
timeit.repeat(stmt, repeat=r, number=n)
r totals
take min()
timeit.Timer(stmt).autorange()
picks n for at least 0.2 s
when you do not know a good n
python -m timeit options: -n N runs per loop, -r R repeats (default 5), -s "code" setup (not timed, repeatable), -u msec unit, -p CPU time instead of wall time.
python -m cProfile -s cumulative report.py | head -25 # print, sorted
python -m cProfile -o report.prof report.py # save for pstats
python -m pstats report.prof # interactive browser: sort, stats 10
def parse (lines: list[ str ]) -> list[ float ]:
return [ float (x) for x in lines]
return sum ( sum (parse([ "21.5" , "22.0" , "19.8" ])) for _ in range ( 100 ))
with cProfile.Profile() as profiler:
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)
pstats call
Does
Stats(profiler) or Stats("report.prof")
load the data
.strip_dirs()
drop folder names from file paths
.sort_stats("cumulative") / "tottime" / "ncalls"
sort; SortKey.CUMULATIVE etc. also work
.print_stats(10)
print the top 10 lines
.print_stats("report")
only lines whose file:line(function) matches the regex
.print_callers("mean")
who calls mean
.print_callees("month_of")
what month_of calls
.dump_stats("out.prof")
save to a file
.get_stats_profile()
data as objects: func_profiles[name].ncalls, .cumtime
Column
Meaning
ncalls
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 profilers: py-spy (sampling, attaches to a running process), line_profiler (time per line), tracemalloc (standard library, memory per line), scalene (CPU and memory).
from collections import Counter, deque
orders = [ 79.99 , 249.0 , 14.99 , 1299.0 , 66.49 , 129.95 ]
valid = { "P001" , "P002" , "P003" } # set: O(1) membership
print ( "P002" in valid, "P999" in valid)
print (Counter([ "Home" , "Books" , "Home" ]).most_common( 1 )) # one pass
print (heapq.nlargest( 2 , orders)) # top k without a full sort
window = deque([ 21.0 , 21.5 , 22.0 ], maxlen = 3 )
window.append( 22.4 ) # drops 21.0 in O(1)
print ( len (prices) - bisect.bisect_left(prices, 100 )) # how many >= 100
Instead of…
Write…
Gain
if x in big_list: in a loop
big_set = set(big_list) once
O ( n ) O(n) O ( n ) → O ( 1 ) O(1) O ( 1 ) per test
scan a list of dicts for a key
index = {r["id"]: r for r in rows}
O ( n ) O(n) O ( n ) → O ( 1 ) O(1) O ( 1 ) per lookup
queue.pop(0)
deque.popleft()
O ( n ) O(n) O ( n ) → O ( 1 ) O(1) O ( 1 )
[labels.count(x) for x in set(labels)]
Counter(labels)
O ( k ⋅ n ) O(k \cdot n) O ( k ⋅ n ) → O ( n ) O(n) O ( n )
s += piece in a loop
"".join(pieces)
one copy
sorted(xs)[-1], sorted(xs)[:10]
max(xs), heapq.nsmallest(10, xs)
less than a full sort
a Python loop over numbers
NumPy array operations
loop in C (module 23)
statistics.mean in a hot loop
sum(xs) / len(xs) or statistics.fmean
no exact fractions
Threads
Processes
asyncio
Helps
I/O-bound
CPU-bound
I/O-bound, many tasks
Parallel Python code
no (GIL)
yes
no
Memory
shared
separate (data is pickled)
shared
Start cost
small
large
tiny
How many
tens
about one per core
thousands
Switches
between any two bytecodes
OS
only at await
Main risk
race conditions
main guard, pickling
blocking calls
GIL in four facts:
In standard CPython, one thread per process runs Python code at a time.
Waiting (sleep, network, disk) releases the GIL, so threads overlap waits.
Many C libraries (NumPy, hashlib, zlib) release it during long work.
Each process has its own GIL. Free-threaded builds (optional since 3.13, officially supported since 3.14) have none.
def check (store_id: str ) -> None :
time.sleep( 0.05 ) # waiting releases the GIL
with lock: # protect shared state
threads = [threading.Thread( target = check, args = ( f "S { i :02d } " ,)) for i in range ( 1 , 5 )]
t.join() # wait for the thread to finish
['S01', 'S02', 'S03', 'S04']
Tool
Use
threading.Lock()
one thread at a time in with lock:
threading.Event()
a flag that threads wait on: event.wait(), event.set()
queue.Queue()
a thread-safe queue for producer and consumer threads
threading.local()
one value per thread, such as a database connection
from concurrent.futures import ThreadPoolExecutor, as_completed
def fetch (page: int ) -> str :
time.sleep( 0.05 * ( 4 - page)) # later pages answer faster
raise TimeoutError ( f "page { page } " )
with ThreadPoolExecutor( max_workers = 4 ) as pool:
print ( list (pool.map(fetch, [ 1 , 2 ]))) # input order
futures = {pool.submit(fetch, p): p for p in [ 1 , 2 , 3 ]}
for future in as_completed(futures): # finish order
results.append(future.result()) # re-raises the task's exception
errors.append(futures[future])
print ( sorted (results), errors)
API
Does
ThreadPoolExecutor(max_workers=n)
thread pool; default min(32, cores + 4)
ProcessPoolExecutor(max_workers=n, mp_context=...)
process pool; default: number of cores
pool.map(func, items, chunksize=1)
results in input order; chunksize batches items for processes
pool.submit(func, *args, **kwargs)
one task → a Future
future.result(timeout=None)
wait; return the value or raise the task’s exception
future.exception(), future.done(), future.cancel()
inspect or cancel
as_completed(futures, timeout=None)
futures in finish order
wait(futures, return_when=FIRST_COMPLETED)
wait for some or all
with Executor(...) as pool:
calls pool.shutdown(wait=True) at the end
A process pool script must run as a file. The template:
from concurrent.futures import ProcessPoolExecutor
def work (chunk: list[ float ]) -> float : # top level: picklable by name
return sum (x * x for x in chunk)
data = [ float (i) for i in range ( 1_000_000 )]
chunks = [data[i:: 8 ] for i in range ( 8 )] # few, large tasks
spawn = multiprocessing.get_context( "spawn" ) # same behavior on every OS
with ProcessPoolExecutor( max_workers = 4 , mp_context = spawn) as pool:
print ( sum (pool.map(work, chunks)))
if __name__ == "__main__" : # required: workers import this file
Rule
Why
main guard if __name__ == "__main__":
with spawn, every worker imports the script
task functions at module level, no lambda
functions are pickled by module and name
small arguments and results
everything is pickled and copied
few, large tasks; chunksize= for many small items
each task costs a message round trip
seed a random.Random(seed) inside each task
the same results in any process, in any order
default start method: spawn (macOS, Windows), forkserver (Linux, 3.14+: a small server process starts each worker), fork (Linux, up to 3.13)
set it with get_context() when it matters
async def fetch (day: str , delay: float , semaphore: asyncio.Semaphore) -> str :
async with semaphore: # at most 2 requests at a time
await asyncio.sleep(delay) # never time.sleep() in a coroutine
async def main () -> list[ str ]:
semaphore = asyncio.Semaphore( 2 )
days = [ "2024-05-01" , "2024-05-02" , "2024-05-03" ]
return await asyncio.gather( * (fetch(d, 0.05 , semaphore) for d in days))
print (asyncio.run(main()))
['2024-05-01: ok', '2024-05-02: ok', '2024-05-03: ok']
API
Does
async def f(): ...
a coroutine function; f() returns a coroutine, it does not run it
await x
pause until x is done; only inside async def
asyncio.run(main())
start the event loop, run main(), close the loop; once per program
asyncio.gather(*aws)
run concurrently; results in argument order
asyncio.gather(*aws, return_exceptions=True)
exceptions come back as values instead of being raised
asyncio.create_task(coro)
schedule a coroutine now; keep a reference to the task
async with asyncio.TaskGroup() as tg:
tg.create_task(...); cancels the rest if one fails (3.11+)
asyncio.Semaphore(n)
at most n tasks inside async with semaphore:
asyncio.sleep(s)
wait without blocking the loop
asyncio.to_thread(func, *args)
run blocking code in a thread (3.9+)
asyncio.timeout(s) / asyncio.wait_for(aw, s)
time limits; raise TimeoutError
asyncio.as_completed(aws)
awaitables in finish order
asyncio.Queue()
producer and consumer tasks
Async libraries: httpx.AsyncClient and aiohttp (HTTP), asyncpg (PostgreSQL), aiofiles (files). In Jupyter, the loop already runs: write await main(), not asyncio.run(main()).
Measure before you optimize. The slow part is rarely where you expect it.
x in list inside a loop is quadratic. Build a set or a dict once, outside the loop.
One perf_counter() run of fast code is noise. Use timeit with number=, and the minimum of repeat().
Profilers add overhead per call. Use cProfile to find the hotspot and timeit to measure the fix. Call counts are exact.
statistics.mean is exact and slow. In hot loops use sum(xs) / len(xs) or statistics.fmean.
sum() of floats is compensated since Python 3.12. A hand-written loop can give a slightly different total.
"x" in df["col"] checks the pandas index, not the values. Use .isin() or a set of the values.
Threads do not speed up pure Python computation on the standard build: the GIL lets one thread run at a time.
Shared state in threads needs a lock , or better, no sharing: return results from tasks.
Process pools need the main guard and top-level functions. Otherwise: RuntimeError (bootstrapping phase) or a pickling error.
Tiny tasks make process pools slower than one process. Send few, large chunks.
as_completed order changes between runs. Use map() or sort the results before you print them.
A coroutine that is not awaited never runs and triggers a “coroutine was never awaited” warning.
time.sleep(), requests.get() or heavy CPU work in a coroutine block every task. Use asyncio.sleep, an async client or asyncio.to_thread.
Create asyncio semaphores, locks and queues inside main(). They bind to the first event loop that waits on them, so module-level ones fail when a program calls asyncio.run() twice.
Unlimited gather against a real API gets you rate-limited. Add a semaphore.