CPU-bound task

In programming, a CPU-bound task is a task whose execution speed is primarily limited by the speed of the central processing unit (CPU) rather than any other system resources, such as memory or input/output (I/O) operations.

CPU-bound tasks typically involve heavy computations, such as mathematical calculations, data processing, or algorithms that require a lot of processing power.

In Python, such tasks can be challenging to optimize due to the Global Interpreter Lock (GIL), which allows only one thread to execute Python bytecode at a time.

When dealing with CPU-bound tasks, you’ll have to find ways to parallelize the workload to leverage multiple CPU cores effectively. One common approach is to use the multiprocessing module to create separate processes for each task, bypassing the GIL and allowing your program to execute tasks concurrently across multiple cores.

Example

Here’s a quick example that shows how you might use the multiprocessing module to handle a CPU-bound task:

Python
import multiprocessing

def compute_square(number):
    return number * number

# Usage
if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5]
    with multiprocessing.Pool() as pool:
        results = pool.map(compute_square, numbers)
    print(results) # Output: [1, 4, 9, 16, 25]

In this example, the compute_square() function is applied to a list of numbers. The multiprocessing.Pool object distributes the tasks across available CPU cores, which significantly improves performance.

Tutorial

Speed Up Your Python Program With Concurrency

In this tutorial, you'll explore concurrency in Python, including multi-threaded and asynchronous solutions for I/O-bound tasks, and multiprocessing for CPU-bound tasks. By the end of this tutorial, you'll know how to choose the appropriate concurrency model for your program's needs.

advanced best-practices

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated April 29, 2025
OSZAR »