我是并行化和 MPI 的新手。我正在学习和试验 mpi4py。目前我正在尝试优化一种方法的性能,该方法在一个间隔内随机采样所需的点(满足条件)。
为了给你一个详细的想法,我创建了一个与我的程序类似的示例程序。该程序的目的是输出 9.9999 和 10.0 之间的 20 个数字。这是通过从 [0.0,1.0] 中随机采样并将其乘以 10 来完成的(通过迭代变化无穷小)。
以下是功能并提供注释。
import numpy as np
import time
def fit(iterations, value):
array = []
sample = None
# This runs for a fixed number of iterations. For one iteration one sample needs to go to the accumulator array (in this case i.e array)
for iteration in range(iterations):
while True:
arbit = np.random.uniform(0,1)
# The main condition for sampling. In my original program this is bound to change with each
# iteration. so I made it depend on the iteration in this test program.
if((10-0.000001*(iteration))*arbit > value):
sample = 10*arbit
break
# The accumulation of accepted sample. If there are n iterations, n samples are expected.
array.append(sample)
print "Result: "+ str(array)
if __name__ == '__main__':
startTime = time.time()
fit(20, 9.9999)
elapsedTime = time.time() - startTime
print "\n"+"time taken: "+str(elapsedTime)+"\n"
如您所见,所有操作都发生在 fit() 方法的 while 循环中。我想做的是利用并行化和 mpi4py 使这种方法更快。例如,我想启动 n 个进程,当 while 循环到来时,这些进程被并行触发,无论哪一个首先找到所需的值,我想将该值添加到累加器数组并中止所有其他进程。我想在下一次迭代中再次继续这个例程,依此类推,直到方法完成。这样的事情可能吗?如果不是这种方式,我可以在上述函数中使用并行化的其他方式吗?
谢谢