2 回答

TA貢獻1829條經驗 獲得超6個贊
微基準測試是一個復雜的問題,因為影響執行時間的因素有很多(例如,即時編譯和垃圾收集)。評論部分已經提供了一個很好的參考,但我建議您也看看我對類似問題的回答,該問題鏈接到Peter Setoft的外部資源,該資源提供了對微基準測試的非常好的介紹以及需要做什么意識到。
已經提到println()在這樣的微基準測試中沒有位置。此外,我想指出您應該使用某種同步機制(例如, a CountDownLatch)來確保四個線程同時開始執行它們的工作。創建和啟動線程所涉及的開銷可能會導致較早的線程在后面的線程啟動所需的時間內搶占先機,從而導致對even鎖的爭用比您預期的要少。例如,這可能看起來像這樣:
public class ExerciseThree {
public static void main(String[] args) {
final CountDownLatch startSignal = new CountDownLatch(1);
final CountDownLatch threadReadyCheck = new CountDownLatch(4);
final CountDownLatch threadDoneCheck = new CountDownLatch(4);
Even even = new Even();
Thread t1 = new Thread(() -> {
threadReadyCheck.countDown();
startSignal.await();
for (int i = 0; i < 100000; i++) {
even.next();
}
threadDoneCheck.countDown();
});
Thread t2 = new Thread(() -> {
threadReadyCheck.countDown();
startSignal.await();
for (int i = 0; i < 100000; i++) {
even.next();
}
threadDoneCheck.countDown();
});
Thread t3 = new Thread(() -> {
threadReadyCheck.countDown();
startSignal.await();
for (int i = 0; i < 100000; i++) {
even.next();
}
threadDoneCheck.countDown();
});
Thread t4 = new Thread(() -> {
threadReadyCheck.countDown();
startSignal.await();
for (int i = 0; i < 100000; i++) {
even.next();
}
threadDoneCheck.countDown();
});
t1.start();
t2.start();
t3.start();
t4.start();
// Wait until all threads are ready to perform their work.
threadReadyCheck.await();
// All threads ready.
// This is where you log start time.
long start = System.nanoTime();
// Let threads progress to perform their actual work.
startSignal.countDown();
// Wait for threads to finish their work.
threadDoneCheck.await();
long end = System.nanoTime();
// Note that this is again subject to many factors, for example when the main thread gets scheduled again after the workers terminate.
long executionTime = end - start;
}
}
添加回答
舉報