【发布时间】:2012-09-30 03:37:09
【问题描述】:
我正在运行一些代码来测试布朗运动和散度,我很好奇这段代码需要多长时间才能运行,以及加速该过程的任何方法。我对java比较陌生,所以目前的代码比较基础。我正在运行的参数是 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);
}
}
提前感谢您的帮助。
【问题讨论】:
-
"运行需要多长时间?" - 在上面放一个计时器并测量它。
-
其复杂度为 O(N*T),因此程序在遇到特定障碍后会显着减速。不过,我真的没有办法改进它。
-
有没有办法让程序使用更多的处理器时间,我注意到我的 cpu 只运行在 12%。
-
@JakeOrben 我的水晶球告诉我,您正在一台有 8 个 CPU 的机器上测试此代码,并且由于该程序不是多线程的,因此您可以尽可能快地运行单个 CPU(因此你提到的 12% 的 CPU 使用率)。
-
你的水晶球是正确的,是否可以编写这个程序来运行多线程?
标签: java performance duration