1、安装:pip install multiprocess
2、
from multiprocessing import Pool
from time import sleep, time
def func1(position):
sleep(4)
return position
if __name__ == '__main__':
with Pool(5) as p:
starttime = time()
print(p.map(func1, range(20)))
print(time()-starttime)
3、对应的执行结果如下:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
16.147092819213867
4、对于涉及到第三方交互、磁盘操作、数据库操作等时,可以通过使用此方法增加并行度和降低整体的时间。同时保留原有执行顺序。理论上,可以解决所有的for循环操作