Fork the process (factorial) - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Fork the process (factorial) (/thread-12670.html) |
Fork the process (factorial) - vndywarhol - Sep-06-2018 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)) RE: Fork the process (factorial) - Vysero - Sep-06-2018 Here's what I got: 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:
RE: Fork the process (factorial) - vndywarhol - Sep-06-2018 In my understanding, even two workers have to reduce time by half, unless I'm wrong? RE: Fork the process (factorial) - ichabod801 - Sep-07-2018 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. |