Using the multiprocessing module to parallelize tasks
suggest changeimport 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents