Using the multiprocessing module to parallelize tasks

suggest change
import multiprocessing

def fib(n):
    """computing the Fibonacci in an inefficient way
    was chosen to slow down the CPU."""
    if n <= 2:
        return 1
    else:
        return fib(n-1)+fib(n-2) 
if __name__ == '__main__':
    # Required when the start method is spawn (Windows, and macOS since Python 3.8).
    p = multiprocessing.Pool()
    print(p.map(fib, [38, 37, 36, 35, 34, 33]))

# Out: [39088169, 24157817, 14930352, 9227465, 5702887, 3524578]

As the execution of each call to fib happens in parallel, the time of execution of the full example is 1.8× faster than if done in a sequential way on a dual processor.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents