I have to do a Monte Carlo simulation using Java. I am in the following situation:
for (int w = 0; w < n; w++) {
for (int t = 0; t < 25; t++) {
for (int a = 0; a < 20; a++) {
// ...calculations...
}
}
}
where n
tends to big really big (order of millions). Moreover, the t
and a
loops (and calculations inside) are INDEPENDENT of the w
loop (I use the w
loop to repeat the matrix calculation n
times). This means, I don't really care which w
is run before or after.
Is there a (possibly not complicate since I have never used parallel programming) way to split the outer for loop and do it synchronously using different threads (e.g. if I have quad-core processor to run using all of them and not just one)?
Edited after @tevemadar solution.
From what I have understood, I can do something like this:
public class MyMonteCarloClass {
private static double[][] monteCarloSums = new double[20][25];
Random generator = new Random();
private void incrementSum() {
for (int t = 0; t < 25; t++) {
for (int a =0; a < 20; a++) {
monteCarloSums[a][t] += generator.nextGaussian();
}
}
}
public double[][] getValue(int numberOfSim) {
IntStream.range(0, numberOfSim).parallel().forEach(I -> incrementSum());
return this.monteCarloSums
}
}
Will something like this speed up with respect having three nested loops?