簡體   English   中英

在這段代碼中,為什么第二個循環執行得比第一個慢?

[英]In this code, why is the second loop executing slower than the first one?

我有使用兩種不同類型的循環的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

現在,為什么會這樣。

您根據以下時間計算時間

fl = stop-start/2;

由於運算符優先級

fl = stop - (start / 2)

我想這不是您想要的,因為在100毫秒后執行它會導致您的fl變量“更長” 50毫秒( (stop + 100) - ((start + 100) / 2) = stop - (start / 2) + 50 )。 這可能是第二個總是“慢”的原因。

的區別, 小真的可以忽略不計,這是很難甚至無法確定什么原因造成的。 您的兩個循環的字節碼相同:

while -loop:

  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 -loop:

 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

這種差異沒有意義,例如6348 / 688721824295 aprox 9-E9。 即,小於1-E6%。

可能是由操作系統處理另一個進程中的線程,殺毒軟件將其踢踢或導致干擾的宇宙射線引起的差異。 這就好比問為什么汽車A在1小時內完成一條路線,而另一輛汽車在1小時又百萬分之一秒內完成路線。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM