gpt4 book ai didi

python - 多处理嵌套Python循环

转载 作者:行者123 更新时间:2023-12-01 03:58:06 24 4
gpt4 key购买 nike

为了改进我的代码,它有一个沉重的循环,我需要加速。如何为这样的代码实现多处理? (a 的典型尺寸为 2,l 的典型尺寸为 10)

for x1 in range(a**l):
for x2 in range(a**l):
for x3 in range(a**l):
output[x1,x2,x3] = HeavyComputationThatIsThreadSafe1(x1,x2,x3)

最佳答案

如果HeavyComputationThatIsThreadSafe1函数仅使用数组而不使用Python对象,我会使用concurrent futures (或 python2 backport )ThreadPoolExecutor 以及 Numba (或 cython )并释放 GIL。否则使用 ProcessPoolExecutor。

参见:

http://numba.pydata.org/numba-doc/latest/user/examples.html#multi-threading

您希望在最外层循环级别并行计算,然后从每个线程/进程产生的 block 中填充输出。这是假设这样做的成本比计算便宜得多,情况应该是这样。

关于python - 多处理嵌套Python循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37092648/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com