python Pool并行执行

 1 # -*- coding: utf-8 -*-
 2 import time
 3 from multiprocessing import Pool
 4 def run(fn):
 5   #fn: 函数参数是数据列表的一个元素
 6   time.sleep(1)
 7   print(fn*fn)
 8 
 9 if __name__ == "__main__":
10   testFL = [1,2,3,4,5,6]
11   print ('順序:') #顺序执行(也就是串行执行,单进程)
12   s = time.time()
13   for fn in testFL:
14     run(fn)
15   t1 = time.time()
16   print ("顺序执行时间:", int(t1 - s))
17 
18   print ('concurrent:')  #创建多个进程,并行执行
19   pool = Pool(10)  #创建拥有10个进程数量的进程池
20   #testFL:要处理的数据列表,run:处理testFL列表中数据的函数
21   pool.map(run, testFL)
22   pool.close() #关闭进程池,不再接受新的进程
23   pool.join() #主进程阻塞等待子进程的退出
24   t2 = time.time()
25   print ("并行执行时间:", int(t2-t1))

执行结果:

猜你喜欢

转载自www.cnblogs.com/lisa2016/p/11256354.html