[英]Why second loop is faster than first
为什么第二个循环比第一个循环快。
public class Test2 {
public static void main(String s[]) {
long start, end;
int[] a = new int[2500000];
int length = a.length;
start = System.nanoTime();
for (int i = 0; i < length; i++) {
a[i] += i;
}
end = System.nanoTime();
System.out.println(end - start + " nano with i < a.length ");
int[] b = new int[2500000];
start = System.nanoTime();
for (int i = b.length - 1; i >= 0; i--) {
b[i] += i;
}
end = System.nanoTime();
System.out.println(end - start + " nano with i > = 0");
}
}
输出是
6776766 nano with i < a.length
5525033 nano with i > = 0
更新 -我已根据建议更新了问题,但我仍然看到时间上的差异。 第一个循环花费更多的时间,然后第二个循环。
这很可能是因为在第一种情况下,您每次迭代都会获取a.length的值,而在第二种情况下则与一次相反。
尝试做类似的事情
int len = a.length;
并使用len作为循环的终止边界。
这可能会减少第一次循环的时间。
如果我稍稍修改了第一个for循环,您将获得类似的时间:
int alength = a.length; // pre-compute a.length
start = System.currentTimeMillis();
for (int i = 0; i < alength; i++) {
a[i] += i;
}
$ java Test
8 millis with i<a.length
6 millis with i>=0
时差的主要原因是-
“ ...除非绝对可以使用+或-15毫秒的精度(这在大多数OS + JVM组合中通常如此
System.currentTimeMillis()
否则请不要使用System.currentTimeMillis()
。请改用System.nanoTime()
。” – Scott Carey 在这里找到
更新:
我相信有人在您的问题的评论部分提到,您还应该在测试微基准测试之前预热测试内核。
规则1:始终包括一个预热阶段,该阶段一直运行测试内核,足以在计时阶段之前触发所有初始化和编译。 (在预热阶段可以进行较少的迭代。经验法则是数以万计的内循环迭代。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.