I’m running some code to test Brownian Motion and divergence, I was curious how long this code will take to run as well as any ways to speed up the process. I am relatively new to java, so the code at the present time is relatively basic. The arguments that I am running are 1000000 1000000.
public class BrownianMotion {
public static void main(String[] args) {
/**starts vars for program*/
int N = Integer.parseInt(args[0]);
int T = Integer.parseInt(args[1]);
double sqtotal = 0;
double r;
double avg;
/**number of trials loop*/
for (int count=0;count<T;count++) {
/**started here so that x & y reset at each trial*/
int x = 0;
int y = 0;
/**loop for steps*/
for (int steps=0;steps<N;steps++) {
r = Math.random();
if (r < 0.25) x--;
else if (r < 0.50) x++;
else if (r < 0.75) y--;
else if (r < 1.00) y++;
}
/**squared total distance after each trial*/
sqtotal = sqtotal + (x*x+y*y);
}
/**average of squared total*/
avg = sqtotal/T;
System.out.println(avg);
}
}
Thanks in advance for the help.
As I understand your code, you could run each trial in parallel. If your CPU has multiple cores it would run faster accordingly.
(EDIT ADDED)
Normally, I’d convert the algorithm into a Callable, create tens of them, (one per dimension, per state, etc.) then use Executors.newFixedThreadPool() to create a thread pool of reasonable size (say, for my might Intel i3 laptop, 4 threads) and call invokeAll(). More details in this blog post
However, in your example of 100,000 this doesn’t work so well. The ideal way would be to use a CompletionService to resubmit jobs as they finish. This starts getting complicated.
A simpler, not as efficient method (but still faster) might be to
they set x and y = 0 at the start they can be reused. So you only
need to create this list once
}
You will waste a bit of time waiting for all to finish, but there should still be a significant speedup. Since most processors have cores in 2,4,8 etc…, a slight improvement would be to make the collection a power of 2 (instead of 10 which makes the math easy)