Sub topic 2
I/O-bound and CPU-bound work
This chapter assumes you can write Python functions and scripts, and that you know the difference between concurrency and parallelism from the previous chapter. Here you will learn to classify a workload as I/O-bound or CPU-bound, and to check that classification with a measurement. That classification decides which concurrency tool will help. Later chapters on threads, the GIL, and processes depend on it.
The two kinds of waiting
Every task spends its time in one of two states:
- Computing. The CPU executes instructions for your program: arithmetic, parsing, hashing, looping, building data structures.
- Waiting. The program is stopped until something outside the CPU finishes: a network reply, a disk read, a database answer, a timer, a child process.
A task is I/O-bound if its total running time is mostly waiting. A faster CPU would barely change how long it takes. A task is CPU-bound if its running time is mostly computing. A faster network or disk would not change it.
The distinction matters because waiting can overlap and computing cannot, unless you have more than one CPU core working on it. While one task waits for a server, another task can use the CPU or start its own wait. If five tasks each wait one second, all five waits can run at the same time and take about one second in total. If five tasks each need one second of computation, finishing in one second requires five cores doing real work at once.
Typical examples
| Workload | Usually | Why |
|---|---|---|
| Downloading many web pages | I/O-bound | Time goes to network latency and transfer. |
| Calling a REST API or database | I/O-bound | The program waits for the remote side. |
| Reading many small files | Mostly I/O-bound | Waiting on the disk or the operating system. |
| Waiting on `time.sleep` or a timer | I/O-bound (no CPU use) | The thread is parked until the timer fires. |
| Resizing images in pure Python | CPU-bound | Every pixel is processed by interpreter code. |
| Computing hashes of in-memory data | CPU-bound | The CPU does all the work. |
| Parsing a large JSON document | CPU-bound | Parsing is computation on data already in memory. |
| Numeric loops, simulations, prime searches | CPU-bound | Pure computation. |
Most real programs are a mix. A web scraper downloads a page (I/O), parses the HTML (CPU), and writes a row to a database (I/O). The question to ask is which part dominates the total time, and whether that part can be separated from the rest.
A rule of thumb that fails sometimes
"Network and disk are I/O, everything else is CPU" is a good first guess, but it breaks in several common cases.
- Fast I/O is not I/O-bound. Reading a file that is already in the operating system's cache, or talking to a server on the same machine, may finish in microseconds. Per-item overhead in your Python code can then dominate, and the task behaves as CPU-bound.
- Large transfers can be CPU-bound. Decompressing, decrypting, or decoding a downloaded payload takes CPU time proportional to its size. A fast network with a large payload shifts the balance toward CPU.
- Memory-bound work. Some tasks neither wait on devices nor do much arithmetic. They are limited by how fast the CPU can read memory, for example scanning huge arrays. These count as CPU-bound from the point of view of Python concurrency, and adding cores can help less than you expect because cores share memory bandwidth.
- Waiting on a lock or a queue. A thread blocked on a lock is waiting, but not for I/O. Its time will not shrink when you add more workers. If many workers contend for one lock, you have a coordination bottleneck rather than either of the two kinds.
- Waiting on another process. Calling
subprocess.runblocks your program while the child works. From your side it is waiting, but if the child is CPU-heavy, the machine is still busy. Look at the whole system, not only your interpreter.
Measuring instead of guessing
You can tell the two kinds apart by comparing two clocks:
time.perf_counter()measures wall-clock time, the real elapsed time.time.process_time()measures CPU time, the time your process actually spent executing on a CPU, summed over all its threads.
For a CPU-bound task the two numbers are close, because the process is busy the whole time. For an I/O-bound task, CPU time is far smaller than wall time, because most of the elapsed time was spent waiting.
import time
def waiting():
time.sleep(1) # stands in for a network call
def computing():
sum(i * i for i in range(3_000_000))
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__:10} wall={wall:.2f}s cpu={cpu:.2f}s cpu/wall={cpu / wall:.0%}")
for task in (waiting, computing):
profile(task)On a typical machine the output looks like this. Exact numbers vary.
waiting wall=1.00s cpu=0.00s cpu/wall=0%
computing wall=0.21s cpu=0.21s cpu/wall=100%The ratio of CPU time to wall time is a quick classifier. A ratio near 0% means mostly waiting. A ratio near 100% means mostly computing. Values in between indicate a mixed task, and you should measure the parts separately.
Finding the dominant part of a mixed task
When one function does both kinds of work, a profiler shows where the time goes. The standard library's cProfile reports time per function. Run it on a representative input:
import cProfile
import pstats
import time
def fetch(n):
time.sleep(0.05) # simulated network wait
return "x" * 200_000
def parse(text):
return sum(ord(c) for c in text)
def pipeline():
total = 0
for n in range(5):
total += parse(fetch(n))
return total
profiler = cProfile.Profile()
profiler.runcall(pipeline)
pstats.Stats(profiler).sort_stats("cumulative").print_stats(5)The report lists fetch and parse with their cumulative times. Here fetch spends its time inside time.sleep, which is waiting, while parse spends it executing Python code, which is computing. Whichever has the larger share is the one worth speeding up first. The two parts may even call for different tools, with threads for the waits and processes for the parsing.
Why the classification drives the tool choice
The rest of this tutorial rests on one idea, shown here as a decision flow. The reasons behind each branch come in the chapters on the GIL and on processes.
In short:
- I/O-bound work gains from overlapping waits. Threads and
asyncioare designed for this. More workers help until the remote service, the disk, or the network link becomes the limit. - CPU-bound work gains only from executing on several cores at the same time. In standard CPython, threads running pure Python code do not do that, which is the subject of the GIL chapters. Separate processes do.
- Neither kind gains from concurrency if the work is already fast. Starting a thread or a process has a cost, and for tiny tasks that cost exceeds the savings.
Limits and edge cases
Overlapping waits has an upper bound. If a task takes 1 second of waiting and 0.1 seconds of computing, then running it 10 times concurrently on one core takes about 1 second of waiting (overlapped) plus 10 × 0.1 = 1 second of computing (not overlapped). The result is about 2 seconds instead of 11. Adding more workers cannot push the total below the computing part, which grows with the number of tasks. As you add workers, the CPU-bound share becomes the bottleneck. This is a form of Amdahl's law: the part you cannot overlap sets the floor.
The same limit appears in reverse for processes. Splitting a CPU-bound job over four cores gives at most a four-times speedup, and in practice less, because of process startup and the cost of moving data between processes. A job that takes 50 ms will often run slower in a process pool than in a plain loop.
Last, the answer can change with the data or the environment. A function that reads from a local SSD may be CPU-bound in testing, then become I/O-bound in production when the data lives on a network drive. Measure in an environment that resembles the real one.
Summary of the working model
- Every task splits into computing time and waiting time.
- A task is I/O-bound when waiting dominates and CPU-bound when computing dominates. Most real tasks are mixed, so classify the dominant part.
- Compare
time.perf_counter()(wall time) withtime.process_time()(CPU time) to measure the split, and usecProfilefor mixed tasks. - Waits can overlap on one core. Computation needs more cores to overlap.
- The classification can change with input size, hardware, and environment, so re-measure when those change.
Exercise
You run a function with the profile helper above and get wall=2.00s and cpu=1.90s. Then you move the same function to a machine where the data is fetched over a slow network, and get wall=6.00s and cpu=1.95s. How would you classify the function in each case, and which of the two situations would benefit from overlapping several calls with threads?
Show answer
On the first machine the CPU/wall ratio is about 95%, so the function is CPU-bound, and threads running pure Python code would not make several calls finish faster. On the second machine the ratio is about 33%. About 4 of the 6 seconds are waiting, so it is mostly I/O-bound, and overlapping several calls would hide much of that waiting. The CPU part (about 1.95 s per call) would still add up across calls, so the total time cannot drop below it.
Exercise
Why can a task that reads a file from the operating system cache behave as CPU-bound even though "file reading" is I/O?
Show answer
When the data is already cached in memory, the read returns almost immediately, so there is little waiting. The remaining time is spent in your own code, for example decoding and processing each line, which is computation. The label "I/O" describes the kind of operation, but the classification depends on where the time actually goes.