這裏是什麼,我會用做一些基本的,而不是精確的測試一個簡單的例子。
首先,我們需要一些基本的方法來啓動和打印時容易
public class Main {
static long start;
static void startTest(){
start = System.nanoTime();
}
static void stopTest(){
System.out.format("%012.6f ms\n",(System.nanoTime() - start)/1000000.0);
start = -1;
}
}
單線程
讓我們運行在一個空的循環測試:
startTest();
for(int i = 0; i < Integer.MAX_VALUE; ++i){}
stopTest();
這將等待該在調用stopTest()
之前循環結束並打印所需的時間。
多線程
隨着不同的線程,你需要等待,他們結束,這是簡單,也可以不以多種方式。這裏是一個:
startTest();
List<Callable<String>> list = new ArrayList();
for(int i=0;i<5;i++){
list.add(new Callable() {
public Object call() throws Exception {
for(int i = 0; i < Integer.MAX_VALUE/5; ++i){}
System.out.println("End of Thread");
return null;
}
});
}
ExecutorService es = Executors.newCachedThreadPool();
try {
es.invokeAll(list);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} finally {
stopTest();
es.shutdown();
}
有了這個Executors
,我們可以在同一時間等待他們結束調用所有Callable
。
花費在循環中的時間取決於花費在其中的方法的時間......所以問題是什麼? – AxelH
可能的重複[如何在Java中編寫正確的微基準測試?](http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java ) – rkosegi