如何并行重复运行一个函数?
例如,我有一个不带参数且具有随机元素的函数。我想多次运行它,如下图所示,使用 for
循环。请问我如何并行完成相同的任务?
import numpy as np
def f():
x = np.random.uniform()
return x*x
np.random.seed(1)
a = []
for i in range(10):
a.append(f())
这是 parallel-python-just-run-function-n-times 的重复项但是,答案不太合适,因为它将不同的输入传递到函数中,并且 How do I parallelize a simple Python loop?还给出了向函数传递不同参数而不是重复相同调用的示例。
我使用的是 Windows 10 并使用 Jupyter
就我的实际用途而言:
Does it produce a large volume of output per call?
Each iteration of the loop produces one number.Do you need to keep the output? How long does each invocation take roughly?
Yes, I need to retain the numbers and it takes ~30 minutes per iteration.?How many times do you need to run it in total?
At least 100.Do you want to parallelize across multiple machines or just multiple cores?
Currently just across multiple cores.
最佳答案
如果您不想向函数传递任何输入,只需使用 Throwaway 变量 _
作为函数的参数并对其进行并行化,如下面的代码所示。
import numpy as np
from multiprocessing.pool import Pool
def f(_):
x = np.random.uniform()
return x*x
if __name__ == "__main__":
processes = 5 # Specify number of processes here
p = Pool(processes)
p.map(f, range(10))
更新: 要回答您更新的问题,如果您的任务不是太重量级并且只是 I/O 绑定(bind),那么我建议您使用 ThreadPool(多线程)而不是 Pool(多处理) )
创建线程池
的代码:
from multiprocessing.pool import ThreadPool
threads = 5
t = ThreadPool(threads)
t.map(f, range(10))
关于python - 重复并行运行一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57581445/