多重处理 python for 循环并将结果保存为字典
Multiprocessing a python for loop and saving results as a dictionary
我正在尝试加速某些 python 代码只能 运行 单线程。我在一个 for 循环中 运行 宁其中的许多,并希望将其并行化并将结果保存在字典中。
我搜索了堆栈溢出并阅读了 multiprocessing
文档,但找不到好的解决方案。
未并行化示例:
%%time
# This only uses one thread! It's slow
mydict = {}
for i in range(20000000):
mydict[i] = i**2
Returns:
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)))
Returns:
TypeError: square() missing 1 required positional argument: 'i'
预期结果是正确的字典,但时间大约是 9.21s 的 1/4。
如果您有一个带有多个参数的目标函数,则需要 pool.starmap()
。 .starmap()
将解压 iterable
中的 argument-tuples 并将其映射到目标函数的参数。
iterable
参数需要此布局才能与 .starmap()
:
一起使用
iterable = [(argA1, argB1), (argA2, argB2) ...]
使用 itertools.repeat()
复制标量的引用,例如您的 d
并使用 zip()
:
创建 argument-tuples 的可迭代对象
pool.starmap(square, zip(itertools.repeat(d), range(20)))
我正在尝试加速某些 python 代码只能 运行 单线程。我在一个 for 循环中 运行 宁其中的许多,并希望将其并行化并将结果保存在字典中。
我搜索了堆栈溢出并阅读了 multiprocessing
文档,但找不到好的解决方案。
未并行化示例:
%%time
# This only uses one thread! It's slow
mydict = {}
for i in range(20000000):
mydict[i] = i**2
Returns:
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)))
Returns:
TypeError: square() missing 1 required positional argument: 'i'
预期结果是正确的字典,但时间大约是 9.21s 的 1/4。
如果您有一个带有多个参数的目标函数,则需要 pool.starmap()
。 .starmap()
将解压 iterable
中的 argument-tuples 并将其映射到目标函数的参数。
iterable
参数需要此布局才能与 .starmap()
:
iterable = [(argA1, argB1), (argA2, argB2) ...]
使用 itertools.repeat()
复制标量的引用,例如您的 d
并使用 zip()
:
pool.starmap(square, zip(itertools.repeat(d), range(20)))