0

我在 Java 中有这段代码,使用两种不同类型的循环。

public class Test {
    public static void main(String[] args){
        long fl = 0, wl = 0; 
        int i = 0;
        int a = 0;
        long start = 0, stop = 0;

        start = System.currentTimeMillis();
        while(i<2000000000){
             if(i%2 == 0)
                a++;
            else
                a--;
            i++;
        }
        stop = System.currentTimeMillis();
        wl = stop-start/2;
        System.out.println("\nWhile loop = "+wl);

        i = 0;
        a = 0;
        start = 0;
        stop = 0;

        start = System.currentTimeMillis();
        for(;i<2000000000;){
            if(i%2 == 0)
                a++;
            else
                a--;
            i++;
        }
        stop = System.currentTimeMillis();
        fl = stop-start/2;
        System.out.println("For loop = "+fl);

        System.out.println("Difference = "+(fl-wl));
    }
}

现在,在多次运行程序后,我得出的结论是第二个循环的执行速度总是比第一个循环慢。起初,我认为它与一个是 for 循环,另一个是一个 while 循环有关,但即使我颠倒了顺序,第二个循环仍然执行得更慢。这是示例运行的输出。

While loop = 688721817947
For loop = 688721824295
Difference = 6348

现在,为什么会发生这种情况。

4

3 回答 3

6

你计算你的时间基于

fl = stop-start/2;

由于运算符优先级

fl = stop - (start / 2)

我猜这不是你想要的,因为在 100 毫秒后执行它会导致你的fl变量“更长”50 毫秒((stop + 100) - ((start + 100) / 2) = stop - (start / 2) + 50)。这可能是第二个总是“慢”的原因。

于 2013-08-25T15:23:19.010 回答
1

这么小的差异真的可以忽略不计,如果不是不可能的话,也很难确定是什么原因造成的。你的两个循环的字节码是相同的:

while-环形:

  21: goto          43
  24: iload         5
  26: iconst_2      
  27: irem          
  28: ifne          37
  31: iinc          6, 1
  34: goto          40
  37: iinc          6, -1
  40: iinc          5, 1
  43: iload         5
  45: ldc           #22                 // int 2000000000
  47: if_icmplt     24

for-环形:

 104: goto          126
 107: iload         5
 109: iconst_2      
 110: irem          
 111: ifne          120
 114: iinc          6, 1
 117: goto          123
 120: iinc          6, -1
 123: iinc          5, 1
 126: iload         5
 128: ldc           #22                 // int 2000000000
 130: if_icmplt     107
于 2013-08-25T15:22:53.223 回答
0

这种差异没有意义,因为6348 / 688721824295aprox 9-E9。即,小于 1-E6 %。

任何事情都可能导致差异,从操作系统处理来自另一个进程的线程或防病毒启动它或造成干扰的宇宙射线。这就像问为什么汽车 A 在 1 小时内完成一条路线,而另一辆在 1 小时 100 万分之一秒内完成。

于 2013-08-25T15:22:39.090 回答