python - Python多进程池的高效实现
问题描述
我有两个代码。一个是另一个的池化(多处理)版本。然而,即使是 1 个处理器的并行版本也需要很长时间,而串行版本则需要大约 15 秒才能完成。有人可以帮助加速第二个版本。
- 串行
import numpy as np, time
def mapTo(d):
global tree
for idx, item in enumerate(list(d), start=1):
tree[str(item)].append(idx)
data=np.random.randint(1,4, 20000000)
tree = dict({"1":[],"2":[],"3":[]})
s= time.perf_counter()
mapTo(data)
e = time.perf_counter()
print("elapsed time:",e-s)
耗时:~15 秒
- 平行
from multiprocessing import Manager, Pool
from functools import partial
import numpy as np
import time
def mapTo(i_d,tree):
idx,item = i_d
l = tree[str(item)]
l.append(idx)
tree[str(item)] = l
manager = Manager()
data = np.random.randint(1,4, 20000000)
# sharedtree= manager.dict({"1":manager.list(),"2":manager.list(),"3":manager.list()})
sharedtree = manager.dict({"1":[],"2":[],"3":[]})
s= time.perf_counter()
with Pool(processes=1) as pool:
pool.map(partial(mapTo, tree=sharedtree), list(enumerate(data,start=1)))
e = time.perf_counter()
print("elapsed time:",e-s)
解决方案
推荐阅读
- angular - Angular 异步管道是如何工作的
- .net - 从 .net core 2.2 迁移到 3.0 => 在 Authenticaton 之前执行授权
- asp.net-core - 无法使用 ADO.Net 配置 Asp.net identity 2.2
- php - 如何在 Azure 应用服务网站上使用“php”
- html - 如何使我的 ReactJS 组件的类名唯一?
- javascript - 包含“。”的数字的问题 像 1.11 或 .111
- android - 根据设备宽度和高度设置字体大小
- amazon-web-services - AWS XRay 在带有 Hapi 的 Typescript 中使用时失败
- haskell - Haskell缩进问题
- c# - 数据表大容量复制到 SQL Server 合并行 ID