Why calculating factorial using multiprocessing is slower than using recursion?

落爺英雄遲暮 提交于 2021-02-10 12:05:05

问题


I'm trying to find a faster way to calculate factorial. In the following code, I first use recursion method , and then I use another method by dividing the whole operation into smaller calculations and then run them in parallel.

Here's my code:

#!/usr/bin/env python3
import time 
from multiprocessing import Pool
import itertools
def fact(n):
    if n==1:
        return 1
    else:
        a=n*fact(n-1)
        return a

def divid(start ,end):
    m=1
    for i in range(start,end+1):
        m=m*i
    return m

pool=Pool()

a=time.time()
res=fact(100)
print (res)
print ("Time spent calculating factorial",(time.time()-a)*60)

a=time.time()
L = pool.starmap(divid,[(1,25),(26,50),(51,75),(76,100)] )

m=1
for i in list(L):
    m=m*i
print ("Result is",m)

print("Time spent calculating factorial using multiprocessing",(time.time()-a)*60)

So running this code for factorial(100) I find out that recursion method is 2 times faster than using multiprocessing.

来源:https://stackoverflow.com/questions/47065460/why-calculating-factorial-using-multiprocessing-is-slower-than-using-recursion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!