簡體   English   中英

為什么長字面量計算需要更多時間?

[英]Why computation takes more time with long literal?

對於簡單的多線程代碼,如下所示,

關閉主線程需要41338 milliseconds ,始終保持類似的延遲

如果我用int替換long ,並且像i < 0x7FFFFFFF一樣進行比較,則需要28 milliseconds時間,且延遲相同。

機器電源:DELL E6430緯度64位機器,運行64位JVM 1.6

public class Dummy {

    private static int NUM_OF_THREADS=200;

    private static Thread[] thread = null;

    public static void loopSomeTime(int i) {
        thread[i] = new Thread(new Runnable(){
            public void run(){
                int count = 0;
                for(long i = 0; i < 0x7FFFFFFFL; ++i){
                    count++;
                }
                System.out.println(count);
            }
        });
        thread[i].start();

    }


    public static void main(String[] args) throws InterruptedException{
        thread = new Thread[NUM_OF_THREADS];
        long beginTime = System.nanoTime();

        for(int i =0; i < NUM_OF_THREADS ; i++){
            loopSomeTime(i);
        }
        //I need to wait here

        for(Thread eachThread : thread){
            eachThread.join();
        }

        long endTime = System.nanoTime() - beginTime;
        System.out.println("Time taken: " +endTime/(1000*1000) + " milliseconds");
    }
}

為了進行比較,我將0x7FFFFFFFL值解釋為等於0x7FFFFFFF的值,即2147483647

請幫助我了解延遲的區別。

代碼不一樣...這是int版本的代碼:

  public void run();
    Code:
       0: iconst_0
       1: istore_1
       2: iconst_0
       3: istore_2
       4: iload_2
       5: ldc           #2                  // int 2147483647
       7: if_icmpge     19
      10: iinc          1, 1
      13: iinc          2, 1
      16: goto          4
      19: getstatic     #3                  // Field java/lang/System.out:Ljava/io/PrintStream;
      22: iload_1
      23: invokevirtual #4                  // Method java/io/PrintStream.println:(I)V
      26: return
}

這是long版本的代碼:

  public void run();
    Code:
       0: iconst_0
       1: istore_1
       2: lconst_0
       3: lstore_2
       4: lload_2
       5: ldc2_w        #2                  // long 2147483647l
       8: lcmp
       9: ifge          22
      12: iinc          1, 1
      15: lload_2
      16: lconst_1
      17: ladd
      18: lstore_2
      19: goto          4
      22: getstatic     #4                  // Field java/lang/System.out:Ljava/io/PrintStream;
      25: iload_1
      26: invokevirtual #5                  // Method java/io/PrintStream.println:(I)V
      29: return
}

您可以觀察到使用的JVM指令是不同的。 int遞增,而long使用算術。 大致: int代碼使用寄存器而不是long寄存器。

這至少可以解釋我和您的計算機上的差異。

它使用了java:

java version "1.8.0_20"
Java(TM) SE Runtime Environment (build 1.8.0_20-b26)
Java HotSpot(TM) 64-Bit Server VM (build 25.20-b23, mixed mode)

和javac

javac 1.8.0_20

在MacOSX 10.9平台上

我的JVM是64位...

暫無
暫無

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

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