Python Forum
Fork the process (factorial)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Fork the process (factorial)
#1
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))
Reply
#2
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
Reply
#3
In my understanding, even two workers have to reduce time by half, unless I'm wrong?
Reply
#4
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Program to Find the Factorial of a Number elisahill 2 1,461 Nov-21-2022, 02:25 PM
Last Post: DeaD_EyE
  computing the factorial of N foolsgold27 12 8,137 Aug-02-2017, 02:29 AM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020