Why is my code slow?
CPU-bound vs waiting-bound work.
🎬 Video version coming soon — read it now
Before you can make code fast, you need to know why it's slow. Almost every slow program is slow for one of two reasons.
1. CPU-bound: the computer is busy calculating
The processor is working flat out: maths on millions of numbers, resizing thousands of images, parsing huge files, training a model.
def count_primes(n):
count = 0
for x in range(2, n):
if all(x % d for d in range(2, int(x ** 0.5) + 1)):
count += 1
return count
count_primes(200_000) # the CPU never restsFixes: a better algorithm or data structure, a library written in C (like NumPy), caching, or using more CPU cores (multiprocessing).
2. I/O-bound: the computer is waiting
The program spends most of its time waiting for something outside: a website to respond, an AI model to answer, a database query, a disk read.
import requests
for url in urls: # 100 websites
requests.get(url) # each waits around 0.5s for the networkThe CPU is almost idle; 100 requests take about 50 seconds of pure waiting.
Fixes: wait for many things at once, with threads or asyncio. While one request waits, others can start.
Why the difference matters
Using the wrong tool doesn't help:
- Threads on CPU-bound pure-Python code: usually no speed-up, because of Python's GIL (global interpreter lock), which lets only one thread run Python code at a time in standard Python
- Multiprocessing on I/O-bound code: works, but wastes memory compared with threads or async
How to tell which you have
- Watch your CPU usage (Task Manager or Activity Monitor) while it runs. Around 100% on one core means CPU-bound; nearly idle means I/O-bound.
- Or time a single step: if one
requests.gettakes 0.5s but the CPU barely moves, you're waiting on the network.
The golden rule
Measure first, then optimise. Developers are notoriously bad at guessing where time goes. The next lesson shows how to measure properly.
In one line
Slow code is either CPU-bound (busy calculating) or I/O-bound (waiting); identify which before choosing a fix.
Share with a friend