我正在尝试加速一些只能运行单线程的Python代码。我在 for 循环中运行其中的许多项,并希望将其并行化并将结果保存在字典中。
我搜索了堆栈溢出并阅读了multiprocessing
文档,但找不到好的解决方案。
未并行化的示例:
%%time
# This only uses one thread! It's slow
mydict = {}
for i in range(20000000):
mydict[i] = i**2
返回:
CPU times: user 8.13 s, sys: 1.04 s, total: 9.17 s
Wall time: 9.21 s
我的字典是正确的
print([mydict[i] for i in range(10)])
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
我的并行化尝试:
%%time
import multiprocessing as mp
from multiprocessing import Process, Manager
def square(d, i):
d[i] = i**2
with mp.Manager() as manager:
d = manager.dict()
with manager.Pool(processes=4) as pool:
pool.map(square, (d, range(20000000)))
返回:
TypeError: square() missing 1 required positional argument: 'i'
预期结果是正确的字典,但时间约为 9.21 秒的 1/4。
最佳答案
如果您的目标函数具有多个参数,则需要pool.starmap()
。 .starmap()
将解压 iterable
中的参数元组并将其映射到目标函数的参数。
iterable
参数需要此布局才能与 .starmap()
一起使用:
iterable = [(argA1, argB1), (argA2, argB2) ...]
使用 itertools.repeat()
复制像 d
这样的标量的引用,并使用 zip()
创建参数元组的可迭代对象>:
pool.starmap(square, zip(itertools.repeat(d), range(20)))
关于python - 多重处理 python for 循环并将结果保存为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56449046/