我正在运行多次重复的模拟,并尝试看看是否可以并行这些重复以缩短计算时间。
目前,我只是在 for 循环中运行模拟几次,但理想情况下,这些都可以同时运行,然后将每次重复的结果保存到数组中进行处理。
目前我的代码类似于
public static void getAllTheData(){
int nReps = 10;
double[][] allResults = new double[nReps][]
//this for loop is what I want to parallellise
for(int r = 0; r < nReps; r++){
//run the simulation to completion here
simulation.doStuffToCompletion()
allResults[r] = simulation.getValues()
}
//average allResults here and do further analysis
}
我的问题是,如何同时并行运行所有这些重复,并将每次并行运行的结果保存在 allResults 类型数组中?
非常感谢。
最佳答案
您可以尝试并行流之类的方法来实现并行性,如下面的行之一。
Stream.of(allResults).parallel().forEach(i -> processData(i));
Arrays.stream(allResults).parallel().forEach(i -> processData(i));
关于java - 如何并行化 for 循环,并将每次重复的结果保存在矩阵中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54868670/