我正在运行一个非常大的for循环,有1000万次迭代。当我一次性执行此操作需要14秒,而当我将其分解为500次小迭代的20次迭代时,它只需要6秒。我无法理解为什么会出现这种行为。我的代码有问题吗?谢谢!
代码
public class Benchmark {
static int max = 10000000;
static int start = 0;
static int end = 0;
static boolean dnc = false;
public static void main(String[] args) {
TimeIt timer = new TimeIt();
timer.printTime("bmTimer dnc false", () -> bmTimer());
dnc = true;
sum = 0;
timer.printTime("bmTimer dnc true", () -> bmTimer());
}
private static void bmTimer() {
if (dnc) {
int factor = 500000;
for (int i = 0; i < max; i += factor) {
end = start + factor;
bm(start, end);
start = end + 1;
}
} else {
bm(0, max);
}
}
static int sum = 0;
private static void bm(int start, int end) {
try {
ExecutorService executor = Executors.newFixedThreadPool(4);
List<Future<String>> futures = new ArrayList<>();
for (int j = start; j < end; j++) {
futures.add(executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
int i = 10;
int j = 9;
return (i - j) + "";
}
}));
}
for (Future<String> future : futures) {
sum += Integer.parseInt(future.get());
}
System.out.println(sum);
executor.shutdown();
executor.awaitTermination(1, TimeUnit.DAYS);
} catch (Exception e) {
e.printStackTrace();
}
}
输出
10000000
Method bmTimer dnc false took : 14.39s
500000
1000000
1500000
2000000
2500000
3000000
3500000
4000000
4500000
5000000
5500000
6000000
6500000
7000000
7500000
8000000
8500000
9000000
9500000
10000000
Method bmTimer dnc true took : 5.856s