Sub topic 2
I/O-bound and CPU-bound work
This chapter assumes you can write Python functions, use with statements, and know that a program can run several tasks at once. You don't need to know threads yet. Everything later in this tutorial depends on one question: what is your task waiting for?
Two reasons a task is slow
A task is slow for one of two reasons.
- I/O-bound work spends most of its time waiting for something outside the CPU. Examples are a network response, a disk read, a database query, or a timer. The CPU is mostly idle.
- CPU-bound work spends most of its time computing. Examples are number crunching, image resizing, compression, and parsing large text in pure Python. The CPU is busy the whole time.
The bottleneck is the resource that limits speed. Waiting on I/O can overlap with other work. Computing can only overlap if there are several cores to compute on.
| Kind | What limits speed | Typical examples | What can help |
|---|---|---|---|
| I/O-bound | Waiting on the outside world | HTTP requests, file reads, SQL queries | Overlapping the waits |
| CPU-bound | Instructions executed per second | Hashing, simulation, pure-Python loops | More cores or faster code |
Measure it instead of guessing
Python has two clocks that expose the difference. time.perf_counter() measures wall-clock time, meaning real elapsed time. time.process_time() measures CPU time, the seconds your process spent executing on a core. Their ratio tells you which kind of work you have.
import time
def io_task():
time.sleep(1) # stands in for waiting on the network
def cpu_task():
total = 0
for i in range(10_000_000):
total += i * i
return total
def profile(fn):
wall_start = time.perf_counter()
cpu_start = time.process_time()
fn()
wall = time.perf_counter() - wall_start
cpu = time.process_time() - cpu_start
print(f"{fn.__name__}: wall {wall:.2f}s, cpu {cpu:.2f}s, cpu/wall {cpu / wall:.2f}")
for task in (io_task, cpu_task):
profile(task)For io_task, wall time is about 1 second and CPU time is near 0, so the ratio is close to 0. For cpu_task, the two times are nearly equal and the ratio is close to 1. Exact numbers depend on your machine.
Why the distinction matters
Overlapping waits is cheap. While one task waits for a server, another can use the CPU or start its own request. Ten downloads that each wait one second can finish in about one second in total. This is concurrency: tasks making progress during overlapping time periods.
Overlapping computation needs real parallelism, which means several cores executing instructions at the same moment. Starting ten compute-heavy tasks on one core only slices that core's time ten ways. Total time does not shrink.
In CPython, the standard Python implementation, a further rule decides which tools can use several cores for Python code. A later chapter covers it: the Global Interpreter Lock. For now, remember that the answer to "will threads help?" depends first on the kind of work.
Common mistakes
- Labelling work by how long it takes. A slow task is not automatically CPU-bound. A ten-second database query is I/O-bound.
- Trusting
time.sleepas a model of CPU work.time.sleepsimulates waiting only. It will make threads look better than they do on real computation. - Ignoring the hidden wait. Code that calls a library may be waiting on a socket inside it. Measure the whole call, not your own lines.
- Benchmarking once. Run several times and use realistic input sizes. Small inputs can make CPU work look like startup noise.
Exercise
A function takes 5 seconds of wall time. Measured with time.process_time(), it uses 0.2 seconds of CPU time. Is it I/O-bound or CPU-bound, and would running 10 copies at once on a single-core machine likely finish much faster than 50 seconds?
Show answer
It is I/O-bound, because the CPU ratio is 0.2 / 5 = 0.04, so it is almost always waiting. Ten copies can overlap their waits, so on one core the total should be far below 50 seconds, roughly 5 to 7 seconds. A CPU-bound function would not speed up this way on one core.