0

我有單班性能測試:單例類有和沒有雙重檢查鎖定

public class Test2 { 

private static Test2 _instance=new Test2(); 

private Test2(){ 

} 

public static synchronized Test2 getInstance(){ 

    if(_instance == null){   
     _instance = new Test2(); 
    } 
    return _instance; 
} 
} 

和兩種實現方式:

public class TestSingleton { 

private static TestSingleton _instance=new TestSingleton(); 

private TestSingleton(){ 

} 

public static TestSingleton getInstance(){ 
    if (_instance == null) { 
     synchronized (TestSingleton.class) { 

      if (_instance == null) { 
     _instance = new TestSingleton(); 
      } 
     } 
    } 
    return _instance; 
} 

我想參數化我發現在所花費的時間方面,有什麼我當時是這樣的:

Callable<Long> task = new Callable<Long>() { 
     @Override 
     public Long call() throws Exception { 
      long start = System.nanoTime(); 
      **TestSingleton.getInstance();** 
      long end = System.nanoTime(); 
      return end - start; 
     } 
    }; 

    for (int i = 0; i < 100000; i++) { 
     futList.add(es1.submit(task)); 
    } 

    for (Future<Long> fut : futList) { 
     try { 
      totalTime1.getAndAdd(fut.get()); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (ExecutionException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
    System.out.println("Time taken by S1 " + totalTime1.get()); 
      . 
      . 
      ExecutorService es2 = Executors.newFixedThreadPool(threadpool); 

    Callable<Long> task1 = new Callable<Long>() { 
     @Override 
     public Long call() throws Exception { 
      long start = System.nanoTime(); 
      Test2.getInstance(); 
      long end = System.nanoTime(); 
      return end - start; 
     } 
    }; 

    for (int i = 0; i < 100000; i++) { 
     futList1.add(es2.submit(task1)); 
    } 

    for (Future<Long> fut : futList1) { 
     try { 
      totalTime2.getAndAdd(fut.get()); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (ExecutionException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
    System.out.println("Time taken by S2 " + totalTime2.get()); 

我得到的結果是:

由S1拍攝時間4636498 時間採取S2 5127865

第一個問題,這是正確的做法?和第二即使我評論的call()兩個getinstances方法,我得到兩個相同的塊的執行時間不同:由S1 1506640採取

時間採取S2 2156172

回答

0

唐 時間」要衡量每次執行和總結時間,單個測量中會出現太多的不準確性。相反,獲得開始時間,執行100000次,獲得結束時間。此外,在開始測量之前執行幾次1000次以避免啓動成本造成的偏差。

相關問題