【Python工具类库】使用进程池加速I/O密集型任务速度

# 随笔

 

# 使用Python进程池加速某些场景下任务速度

# -*- encoding: utf-8 -*-
"""
@File    : bt.py
@Time    : 2020/5/9 17:27
@Author  : xuluda
@Email   : xuluda@163.com
@Software: PyCharm
"""
from multiprocessing import Pool
import time


def show(iq):
    time.sleep(1)
    save_path = '/opt/temp/' + iq + '.jpg'
    print(save_path)


pool = Pool(processes=4)
pic_url_list = range(0, 100)
start_time = time.time()
for i in pic_url_list:
    # 维持执行的进程总数为processes,当一个进程执行完毕后会添加新的进程进去
    pool.apply_async(show, args=(i,))
print('======  apply_async  ======')
pool.close()
# 调用join之前,先调用close函数,否则会出错。执行完close后不会有新的进程加入到pool,join函数等待所有子进程结束
pool.join()
print('耗时:' + str(time.time() - start_time))

 

posted @ 2020-05-09 17:34  nowbug  阅读(304)  评论(0)    收藏  举报