我在 Python 中编写了以下代码:
from concurrent.futures import ProcessPoolExecutor, \
ThreadPoolExecutor, \
as_completed
import random
import time
def addS(v):
s=0
start=time.time()
for i in range(0,len(v)):
s=s+v[i]
start1=time.time()
print ("sec time ",start1-start," sum is ",s)
def dummyFun(l):
s=0
for i in range(0,len(l)):
s=s+l[i]
return s
def main():
workers=4
v = [random.randint(1,101) for _ in range(1000000)]
addS(v)
dim=(int)(len(v)/(workers*10))
s=0
chunks=(v[k:k+dim] for k in range(0,len(v),(int)(len(v)/(workers*10))))
start=time.time()
with ProcessPoolExecutor(max_workers=4) as executor:
futures=[executor.submit(dummyFun,chunk) for chunk in chunks]
start1=time.time()
for future in as_completed(futures):
s=s+future.result()
print ("concurrent time ",start1-start," sum is ",s)
当我使用ProcessPoolExecutor()
我的结果如下:
sec time 0.06529831886291504 sum is 51004089
concurrent time 0.5757372379302979 sum is 51004089
我也改成,ThreadPoolExecutor()
结果是:
sec time 0.06471061706542969 sum is 50981197
concurrent time 0.09298276901245117 sum is 50981197
另外,当我将max_workers
参数设置为时None
,我得到以下结果:
sec time 0.06425285339355469 sum is 50983899
concurrent time 0.09010934829711914 sum is 50983899
如何提高并发时间?因为连续时间一直在变快,还是有原因?