我正在玩一些代碼,計算計算某些Java代碼以獲得某些Java功能的效率或低效率所需的時間。這樣做,我現在卡住了一些非常奇怪的效果,我無法解釋自己。也許你的某個人可以幫助我理解它。Java效率
public class PerformanceCheck {
public static void main(String[] args) {
List<PerformanceCheck> removeList = new LinkedList<PerformanceCheck>();
int maxTimes = 1000000000;
for (int i=0;i<10;i++) {
long time = System.currentTimeMillis();
for (int times=0;times<maxTimes;times++) {
// PERFORMANCE CHECK BLOCK START
if (removeList.size() > 0) {
testFunc(3);
}
// PERFORMANCE CHECK BLOCK END
}
long timeNow = System.currentTimeMillis();
System.out.println("time: " + (timeNow - time));
}
}
private static boolean testFunc(int test) {
return 5 > test;
}
}
開始這導致在一個相對長的計算時間(記住removeList是空的,所以testFunc甚至不叫):
time: 2328
time: 2223
...
雖然更換removeList.size的組合的任何東西()> 0和testFunc(3)都有更好的結果。例如:
...
if (removeList.size() == 0) {
testFunc(3);
}
...
結果(testFunc被稱爲每一次):
time: 8
time: 7
time: 0
time: 0
即使調用兩個功能獨立於在較低計算時間彼此的結果:
...
if (removeList.size() == 0);
testFunc(3);
...
結果:
time: 6
time: 5
time: 0
time: 0
...
在我最初的例子中,只有這個特定的組合需要很長時間。這令我很不快,我真的很想理解它。這有什麼特別之處?
謝謝。
增加:
在第一個例子
if (removeList.size() > 0) {
testFunc(times);
}
別的東西改變testFunc(),像
private static int testFunc2(int test) {
return 5*test;
}
會導致快速再之中。
而且你不止一次運行這個測試,並且以不同的順序對吧?順序應該不重要,但只是爲了確保。另外,你是否得到(約)與nanoTime相同的結果如下所示? – prelic
這種微型基準測試是一個非常糟糕的主意。也意識到JIT可以在任意時間做出各種決定,並完全優化您的代碼,只要它意識到實際上沒有發生任何事情。 –
您應該使用[System.nanoTime()](http://docs.oracle.com/javase/6/docs/api/java/lang/System.html#nanoTime%28%29)在Java中測量代碼執行。它更精確。更多討論[在這個問題](http://stackoverflow.com/questions/351565/system-currenttimemillis-vs-system-nanotime) – paislee