Python Forum

Full Version: Fork the process (factorial)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello! I'm trying to fork out the calculation of factorial using multiprocessing. I'm new to this, but it seemed to me that using Pool could solve my problem. I want to use a certain number of workers that would parallelize the calculations. The problem is that I did not get any effect and multiprocessing works as if only one process is involved. What's wrong with my code?

from multiprocessing import Pool
import time


def factorial(number):
    total = 1
    while number != 1:
        total = total * number
        number = number - 1
    print(total)


if __name__ == '__main__':
    time_start = time.time()
    workers_count = 4
    pool = Pool(processes=workers_count)  # start 4 worker processes
    res = pool.apply_async(factorial, (75000,))  # evaluate
    res.get()
    time_end = time.time()
    print("time with 4 multiprocessing: " + str(time_end - time_start))

    time_start = time.time()
    factorial(75000)
    time_end = time.time()
    print("time as usual: " + str(time_end - time_start))
Here's what I got:
Output:
22142807374883101672219837615212451194.... time with 4 multiprocessing: 2.968395948410034 22142807374883101672219837615212451194.... time as usual: 2.9568259716033936
As you can see the multi-threading process is taking more time on the whole but only slightly. Is this not the output you were looking for?

If you increase workers_count to 8:

Output:
time with 4 multiprocessing: 2.882293462753296 time as usual: 2.949413776397705
In my understanding, even two workers have to reduce time by half, unless I'm wrong?
I'm no expert on multiprocessing, but wouldn't you need to split the task up to take advantage of that? It looks like you're just getting the same number four times simultaneously. You need to multiply 1 to N. I would think you would break 1 to N up into four chunks, have four processors work on the four chunks, and then multiply the four answers to get the final result. Something like this example.