RoS*_*oSt 5 python multiprocessing
我有一个问题,类似于:
import numpy as np
C = np.zeros((100,10))
for i in range(10):
C_sub = get_sub_matrix_C(i, other_args) # shape 10x10
C[i*10:(i+1)*10,:10] = C_sub
Run Code Online (Sandbox Code Playgroud)
因此,显然不需要将其作为连续计算运行,因为每个子矩阵可以独立计算.我想使用多处理模块并为for循环创建最多4个进程.我阅读了一些关于多处理的教程,但是无法弄清楚如何使用它来解决我的问题.
谢谢你的帮助
并行化该代码的一个简单方法是使用Pool进程:
pool = multiprocessing.Pool()
results = pool.starmap(get_sub_matrix_C, ((i, other_args) for i in range(10)))
for i, res in enumerate(results):
C[i*10:(i+1)*10,:10] = res
Run Code Online (Sandbox Code Playgroud)
我之所以使用starmap该函数,是因为该get_sub_matrix_C函数有多个参数(starmap(f, [(x1, ..., xN)])调用f(x1, ..., xN))。
但请注意,序列化/反序列化可能需要大量时间和空间,因此您可能必须使用更底层的解决方案来避免这种开销。
您似乎正在运行过时的 python 版本。您可以替换starmap为 plain map,但随后您必须提供一个采用单个参数的函数:
def f(args):
return get_sub_matrix_C(*args)
pool = multiprocessing.Pool()
results = pool.map(f, ((i, other_args) for i in range(10)))
for i, res in enumerate(results):
C[i*10:(i+1)*10,:10] = res
Run Code Online (Sandbox Code Playgroud)