并行化该代码的一个简单方法是使用Pool https://docs.python.org/3.5/library/multiprocessing.html#multiprocessing.pool.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
我用过starmap https://docs.python.org/3.5/library/multiprocessing.html#multiprocessing.pool.Pool.starmap自从get_sub_matrix_C
函数有多个参数(starmap(f, [(x1, ..., xN)])
calls f(x1, ..., xN)
).
但请注意,序列化/反序列化可能需要大量时间和空间,因此您可能必须使用更底层的解决方案来避免这种开销。
您似乎正在运行过时的 python 版本。您可以更换starmap
与平原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