1 回答

TA貢獻1820條經驗 獲得超2個贊
博士
Duration.between( // Represent a span-of-time as a count of nanoseconds, to be calculated as hours-minutes-seconds.
then , // Earlier in your code, capture the previous current moment: `Instant then = Instant.now() ;`
Instant.now() // Capture the current moment.
) // Returns a `Duration` object, our elapsed time.
.toNanos() // Get the total number of nanoseconds in the entire span-of-time. Returns a `long`.
捕捉當前時刻
您的代碼正在捕獲當前時刻,快照,凍結。生成的對象不會更新。這就是短語“特定時刻”在 JavaDoc 類中的含義。
若要跟蹤經過的時間,必須捕獲當前時刻兩次,從而生成兩個單獨的對象。
避免使用傳統的日期時間類
這個類很糟糕,幾年前被Java.time類所取代,采用了JSR 310。具體來說,替換 ,通常實現 。CalendarZonedDateTimeGregorianCalendarCalendar
Instant
跟蹤當前時刻的現代方法使用類。表示 UTC 中的某個時刻。InstantInstant
Instant start = Instant.now() ;
… // Do some stuff.
Instant stop = Instant.now() ;
分辨率
在 Java 9 及更高版本中,當前時刻以微秒(小數秒的 6 位小數點)的分辨率捕獲。在Java 8中,較早的即時實現僅限于以毫秒為單位捕獲當前時刻(3位小數)。在所有版本的Java中,該類能夠以納秒(9個十進制數字)表示一個時刻。但是傳統的計算機時鐘無法如此精細地精確地跟蹤時間。ClockInstant
Duration
將已用時間計算為持續時間對象。
Duration duration = Duration.between( start , stop ) ; // Represents a span of time in terms of hours-minutes-seconds.
long nanoseconds = duration.toNanos() ; // Converts this duration to the total length in nanoseconds expressed as a long.
System.nanoTime
對于微量標記,您可能需要使用系統時間()。該方法將當前時刻捕獲為自某個任意起點以來的納秒數。請注意:根據任何時鐘或日歷,此返回的值不代表當前時刻。但它對于以可能比 更精細的分辨率跟蹤經過的時間很有用。Instant
long start = System.nanoTime() ; // Some arbitrarily defined count of nanoseconds. *NOT* the current time/date by any clock/calendar.
… // Do some stuff.
long stop = System.nanoTime() ;
long nanoseconds = ( stop - start ) ;
JEP 230: 微床標志套件
對于嚴肅的基準測試,請查看基于JMH的Java 12及更高版本中新增的內置基準測試框架。參見JEP 230:微板標記套件。
添加回答
舉報