0
我試圖用Java 8的LocalTime和Instant實現一個計數器,兩者都正常工作,但輸出結果有點混亂!當我使用Instant時,我在同一個循環中獲得較小的值?任何想法?在Java 8中實現計數器的最佳方式是什麼?
// using Instant
Instant before=Instant.now();
// something time consuming
for(int i=1;i<100000000;i++);
Instant after=Instant.now();
Duration duration=Duration.between(before, after);
System.out.println(duration.toMillis());
// using LocalTime
LocalTime xBefore=LocalTime.now();
for(int i=1;i<100000000;i++);
LocalTime yAfter=LocalTime.now();
System.out.println(ChronoUnit.MILLIS.between(xBefore, yAfter));
謝謝你提到Holger! –
*經過時間*和現實世界(「掛鐘」)時間之間存在顯着差異,因爲系統時鐘可能受到NTP校正等影響。如果您想測量*經過時間*,請使用['System.nanoTime()'](https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#nanoTime- - )並計算差異。但正常情況下,執行時間會隨着JVM的優化器的工作而降低。您可以在鏈接的問答中閱讀更多內容...... – Holger