2 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個(gè)贊
微基準(zhǔn)測(cè)試是一個(gè)復(fù)雜的問題,因?yàn)橛绊憟?zhí)行時(shí)間的因素有很多(例如,即時(shí)編譯和垃圾收集)。評(píng)論部分已經(jīng)提供了一個(gè)很好的參考,但我建議您也看看我對(duì)類似問題的回答,該問題鏈接到Peter Setoft的外部資源,該資源提供了對(duì)微基準(zhǔn)測(cè)試的非常好的介紹以及需要做什么意識(shí)到。
已經(jīng)提到println()在這樣的微基準(zhǔn)測(cè)試中沒有位置。此外,我想指出您應(yīng)該使用某種同步機(jī)制(例如, a CountDownLatch)來確保四個(gè)線程同時(shí)開始執(zhí)行它們的工作。創(chuàng)建和啟動(dòng)線程所涉及的開銷可能會(huì)導(dǎo)致較早的線程在后面的線程啟動(dòng)所需的時(shí)間內(nèi)搶占先機(jī),從而導(dǎo)致對(duì)even鎖的爭(zhēng)用比您預(yù)期的要少。例如,這可能看起來像這樣:
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;
}
}
添加回答
舉報(bào)