这篇博客是按照博客《进程和线程(1)》中内容用futures改写 with futures.ProcessPoolExecutor() as executor:可以两篇博客对照看。
2改写
from multiprocessing import Pool from time import sleep from concurrent import futures def f(x): return x*x def speak(word): for i in range(3): print('i am speak:',word,i) if __name__=='__main__': x=[1,2,3] speak(x) with futures.ProcessPoolExecutor() as executor: print(list(executor.map(f,x))) print(type(executor.map(f,x))) # i am speak: [1, 2, 3] 0 # i am speak: [1, 2, 3] 1 # i am speak: [1, 2, 3] 2 # [1, 4, 9] # <class 'generator'>
2.1.2改写
from multiprocessing import Pool,Process import time from concurrent import futures def f(x): time.sleep(2) print(x*x) return x*x def speak(word): for i in range(3): print('i am speak:',word,i) time.sleep(2) if __name__=='__main__': startTime=time.time() x=[1,2,3] # for i in x: # p=Process(target=f,args=(i,)) # p.start() # endTimeSub=time.time() # print('usetimesub',endTimeSub-startTime) with futures.ProcessPoolExecutor() as executor: executor.map(f,x) endTimeSub=time.time() print('usetimesub',endTimeSub-startTime) endTimeMain=time.time() print('useTime',endTimeMain-startTime) # usetimesub 0.1450958251953125 # 1 # 4 # 9 # useTime 2.2364883422851562
在上面改写基础上,如果在子进程中停顿3s,看看结果怎么样?
from multiprocessing import Pool,Process import time from concurrent import futures def f(x): time.sleep(2) print(x*x) return x*x def speak(word): for i in range(3): print('i am speak:',word,i) time.sleep(2) if __name__=='__main__': startTime=time.time() x=[1,2,3] # for i in x: # p=Process(target=f,args=(i,)) # p.start() # endTimeSub=time.time() # print('usetimesub',endTimeSub-startTime) with futures.ProcessPoolExecutor() as executor: executor.map(f,x) endTimeSub=time.time() time.sleep(3) print('usetimesub',endTimeSub-startTime) endTimeMain=time.time() print('useTime',endTimeMain-startTime) # 1 # 4 # 9 # usetimesub 0.1621077060699463 # useTime 3.2041215896606445
可见:1、总使用只时间增加了1s左右;2、主程序没有继续往下走,先等子进程全部执行完再往下走,useTime都是在最后,直接使用p=Process(target=f,args=(i,)),则是新开一个子进程,主进程继续往下走,注意两者区别;3、比较两者执行时间