python - 多重处理 python for 循环并将结果保存为字典

标签 python python-3.x python-multiprocessing

我正在尝试加速一些只能运行单线程的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/

相关文章:

python - 我已经附上了我的代码。请查看并告诉我错误的原因。解释一下?

python-3.x - 具有异步功能的 Python 多处理

Python REPL : issuing commands in advance to execute after block

python - 当我尝试将数据框转换为 Excel 文件时,列顺序被破坏

Python: elasticsearch.exceptions.NotFoundError: NotFoundError(404, '{"code":404 ,"message":"HTTP 404 Not Found"}')

python - 尝试创建一个仅包含唯一数字的排序列表

python - 来自一个多处理管理器的多个队列

NLTK word_tokenizer 的 Python 多重处理 - 函数永远不会完成

python - IntelliJ Python 3 检查 "Expected a dictionary, got a dict"是否是带有 **kwargs 的 super 的误报?

python - asyncio 收集产生的结果