示例代碼
import multiprocessing
def process_data(data):
# 這里是處理單個數據的過程
return data * 2
# 待處理的數據
data = [1, 2, 3, 4, 5]
def normal_func():
# 普通處理方式
result = []
for obj in data:
result.append(process_data(obj)
return result
def parallel_func():
# 多進程處理方式
pool = multiprocessing.Pool(multiprocessing.cpu_count())
result = pool.map(process_data, data)
pool.close()
return result
if __name__ == '__main__':
result = normal_func()
result = parallel_func()
multiprocessing.Pool
創(chuàng)建進程池, 傳入的參數是要要使用的 CPU 內核數量, 直接用 cpu_count()
可以拿到當前硬件配置所有的 CPU 內核數.
pool.map
可以直接將處理后的結果拼接成一個 list 對象文章來源:http://www.zghlxwxcb.cn/news/detail-703613.html
應用在實際數據處理代碼的效果對比:文章來源地址http://www.zghlxwxcb.cn/news/detail-703613.html
- 普通處理方式, 用時 221 秒
- 多進程處理方式, 用時 39 秒, 節(jié)省了 82% 的時間
到了這里,關于使用 multiprocessing 多進程處理批量數據的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!