What is a CPU-Bound Task?
A CPU-bound task is an operation where the program spends most of its time using the CPU for heavy computation, rather than waiting for input/output (I/O).
-
CPU-bound tasks max out your processor’s power.
-
Performance is limited by how fast the CPU can crunch numbers or run algorithms.
Examples of CPU-Bound Tasks in Python
-
Mathematical Computations
# Calculating factorial recursively (CPU-intensive for large numbers) def factorial(n): return 1 if n == 0 else n * factorial(n-1) print(factorial(1000))
-
Image Processing
from PIL import Image, ImageFilter img = Image.open("large_image.jpg") blurred = img.filter(ImageFilter.GaussianBlur(20)) # heavy pixel computation
-
Data Processing / Machine Learning
# Sorting a huge list (O(n log n)) numbers = list(range(10**7, 0, -1)) numbers.sort() # CPU is busy crunching
CPU-Bound vs I/O-Bound
Aspect | CPU-Bound Task | I/O-Bound Task |
---|---|---|
Bottleneck | CPU speed (computation-heavy) | Waiting on external resources (disk, network) |
Examples | Image processing, ML training, encryption | File I/O, API calls, DB queries |
Best Solution | Multiprocessing (use multiple cores) | Multithreading / Async I/O (overlap waiting) |
Why It Matters
-
For CPU-bound tasks, multithreading doesn’t help much in Python (due to the Global Interpreter Lock — GIL).
-
Instead, you should use multiprocessing so that multiple CPU cores can work in parallel.
✅ Rule of Thumb:
-
Use multiprocessing for CPU-bound tasks.
-
Use multithreading/async for I/O-bound tasks.