Python CPU-bound and I/O-bound Work
What you will learn
- Two reasons a program is slow: computing or waiting
- CPU-bound and I/O-bound work
- Telling them apart: wall time versus CPU time
- Concurrency versus parallelism
- Which Python tool suits which kind of work
1. Why chapter 20?
So far, every program did one thing at a time: line after line. That is fine until a program must handle many things: download 50 web pages, resize 1,000 images, answer many users together, or keep a window responsive while something heavy runs in the background. Concurrency is the family of techniques for doing several things at once, or seemingly at once. The right technique depends on why the program is slow, which is what this lesson is about.
2. Two kinds of slowness
A program spends its time in one of two ways:
| Kind | The program is... | Examples |
|---|---|---|
| CPU-bound | computing: the processor is busy all the time | maths, image processing, compressing, sorting huge data, a game's physics |
| I/O-bound (input/output) | waiting for something outside: a disk, a network reply, a database, a user | downloading pages, reading many files, calling an API, waiting for input() |
A simple test program shows the difference. Two functions:
import time
def cpu_task(n):
"""CPU-bound: the processor is busy the whole time."""
total = 0
for i in range(n):
total += i * i
return total
def io_task(seconds):
"""I/O-bound: the program just waits (like waiting for a network reply)."""
time.sleep(seconds)
return seconds
Running them one after another (timings from one Windows laptop):
1 CPU task 0.20 s
4 CPU tasks, one after other 0.68 s
1 wait of 0.5 s 0.50 s
4 waits, one after other 2.00 s
Four tasks took about four times as long as one, in both cases. But the two kinds differ in an important way:
- During the waits, the processor is idle. Nothing prevents other work from happening at the same time: four waits could all take 0.5 s together.
- During the calculations, the processor is busy. The only way to finish sooner is to use more processors (or a faster algorithm, lesson 18.5).
Quick check: is downloading ten web pages one by one CPU-bound or I/O-bound?
I/O-bound: nearly all the time is spent waiting for the network.
3. How to tell: wall time and CPU time
Two clocks reveal what a program is doing:
- Wall-clock time,
time.perf_counter(): the real elapsed time, as on a wall clock. - CPU time,
time.process_time(): the time the processor actually spent running your code (sleeping and waiting do not count).
import time
def classify(name, func, *args):
wall_start = time.perf_counter()
cpu_start = time.process_time()
func(*args)
wall = time.perf_counter() - wall_start
cpu = time.process_time() - cpu_start
share = cpu / wall
kind = ("CPU-bound" if share > 0.8
else "I/O-bound (mostly waiting)" if share < 0.2 else "mixed")
print(f"{name:<14} wall {wall:5.2f} s cpu {cpu:5.2f} s busy {share:4.0%} -> {kind}")
Trying it on a calculation, a wait, and a mixture of both:
calculation wall 0.26 s cpu 0.27 s busy 103% -> CPU-bound
waiting wall 0.50 s cpu 0.00 s busy 0% -> I/O-bound (mostly waiting)
both wall 0.33 s cpu 0.08 s busy 24% -> mixed
- If CPU time is close to wall time, the program is CPU-bound. (It can even read slightly above 100 percent because of clock rounding, as in the first line.)
- If CPU time is far below wall time, the program is waiting: I/O-bound.
- In real programs, use the profiler (lesson 18.5) to find which part is which.
4. Concurrency and parallelism
Two words that are often confused:
| Word | Meaning | Picture |
|---|---|---|
| concurrency | managing several tasks that are in progress at the same time, switching between them | one cook preparing three dishes, moving between pots while waiting |
| parallelism | running several tasks at the exact same moment, on several processors | three cooks, each with a pot |
Concurrency helps with waiting: while one task waits, another can use the time. Parallelism helps with computing: it needs more than one processor. A computer today usually has several processor cores (os.cpu_count() tells you how many). A program can use concurrency without parallelism, and the reverse.
5. Python's tools
Python offers a tool for each situation. The following lessons show each in turn:
| Tool | How it works | Best for |
|---|---|---|
threads (threading, lesson 20.2) |
several flows of control inside one program, sharing memory | I/O-bound work, simple background jobs |
processes (multiprocessing, lesson 20.3) |
separate Python programs working together, each with its own memory | CPU-bound work, using several cores |
concurrent.futures (lesson 20.4) |
one friendly interface over threads or processes | most everyday needs |
asyncio (lesson 20.5) |
one thread that switches between tasks whenever one waits (async/await) |
very many I/O-bound tasks (thousands of connections) |
A rough guide:
Is the work mostly waiting (network, files, databases)?
yes -> threads (few tasks), or asyncio (very many tasks)
no -> is it heavy computing?
yes -> processes (or a faster algorithm, or libraries written in C such as NumPy)
no -> you probably do not need concurrency
Lesson 20.6 explains why Python's Global Interpreter Lock makes the CPU-bound case different, and how to choose.
6. Before you reach for concurrency
Concurrency makes programs harder: tasks interfere with each other, errors are harder to find, and results can differ from run to run. First ask:
- Is it slow at all? Measure (lesson 18.5).
- Is there a better algorithm or data structure? (A set instead of a list scan made one program about a hundred times faster in lesson 18.5, with no concurrency at all.)
- Can a library do it faster? Vectorised libraries such as NumPy do heavy computing in compiled code.
- Can the work be batched? One database query for 100 rows beats 100 queries.
- Only then: concurrency, in the simplest form that works (usually
concurrent.futures).
Worked example: sorting tasks into the right category
For each job, decide the kind of slowness, and a first tool to try.
| Job | Where the time goes | Kind | First tool |
|---|---|---|---|
| download 100 web pages | waiting for servers | I/O-bound | threads (or asyncio) |
| read 5,000 small files from a network drive | waiting for the drive | I/O-bound | threads |
| resize 2,000 photos | computing pixels | CPU-bound | processes |
| find primes up to 10 million | computing | CPU-bound | a better algorithm first; then processes |
| answer 10,000 chat connections | waiting for messages | I/O-bound, very many | asyncio |
| a sum over a million numbers | computing, but tiny | CPU-bound | sum, or NumPy; no concurrency needed |
| save a file while the window stays responsive | waiting for the disk | I/O-bound | a background thread |
| read a user's input | waiting for a person | I/O-bound | nothing: it is meant to wait |
To confirm a guess in your own program, run it with the wall-clock and CPU-time check of section 3: a low "busy" share means waiting (concurrency with threads or asyncio can overlap the waits), and a share near 100 percent means computing (only more processors, or a faster algorithm, help).
The jobs are examples chosen for the lesson, not measured here.
Common mistakes
- Using threads to speed up heavy calculations (they do not, lesson 20.6).
- Using processes for tiny tasks, where the start-up cost is larger than the work.
- Adding concurrency before measuring or before improving the algorithm.
- Confusing concurrency with parallelism.
- Assuming that more workers is always faster: each extra worker adds cost, and shared resources (a network, a disk, a server's rate limit) become the limit.
- Hammering someone else's server with hundreds of simultaneous requests (lesson 17.11).
- Forgetting that results can arrive in a different order.
Key takeaways
- A program is either CPU-bound (computing) or I/O-bound (waiting), or a mixture.
- Compare
time.perf_counter()(wall time) withtime.process_time()(CPU time) to tell which. - Waiting can overlap with other work (concurrency); computing needs more processors (parallelism).
- Threads and
asynciosuit I/O-bound work; processes suit CPU-bound work;concurrent.futuresoffers one interface for threads and processes. - Measure first and fix the algorithm first; concurrency adds complexity.
Practice
1. Is resizing 1,000 photos CPU-bound or I/O-bound?
Show answer
Mainly CPU-bound (the pixel calculations), with some I/O for reading and writing the files.
2. A function takes 2.0 s of wall time but only 0.05 s of CPU time. What does that tell you?
Show answer
It spends nearly all its time waiting, so it is I/O-bound; overlapping several such calls could save a lot of time.
3. What is the difference between concurrency and parallelism?
Show answer
Concurrency is managing several tasks in progress by switching between them; parallelism is actually running tasks at the same moment on several processors.
4. Which Python tool is aimed at CPU-bound work on several cores?
Show answer
Processes (multiprocessing, or concurrent.futures.ProcessPoolExecutor).
5. Name two things to try before adding concurrency.
Show answer
Measure where the time goes, and look for a better algorithm or data structure (or a faster library or batching).
6. Why is it risky to start hundreds of simultaneous requests to a website?
Show answer
It may overload the server or break its rules, getting you blocked; limit the number of concurrent requests and respect the site's terms.