1 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超3個(gè)贊
博士
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`.
捕捉當(dāng)前時(shí)刻
您的代碼正在捕獲當(dāng)前時(shí)刻,快照,凍結(jié)。生成的對(duì)象不會(huì)更新。這就是短語(yǔ)“特定時(shí)刻”在 JavaDoc 類中的含義。
若要跟蹤經(jīng)過的時(shí)間,必須捕獲當(dāng)前時(shí)刻兩次,從而生成兩個(gè)單獨(dú)的對(duì)象。
避免使用傳統(tǒng)的日期時(shí)間類
這個(gè)類很糟糕,幾年前被Java.time類所取代,采用了JSR 310。具體來說,替換 ,通常實(shí)現(xiàn) 。CalendarZonedDateTimeGregorianCalendarCalendar
Instant
跟蹤當(dāng)前時(shí)刻的現(xiàn)代方法使用類。表示 UTC 中的某個(gè)時(shí)刻。InstantInstant
Instant start = Instant.now() ;
… // Do some stuff.
Instant stop = Instant.now() ;
分辨率
在 Java 9 及更高版本中,當(dāng)前時(shí)刻以微秒(小數(shù)秒的 6 位小數(shù)點(diǎn))的分辨率捕獲。在Java 8中,較早的即時(shí)實(shí)現(xiàn)僅限于以毫秒為單位捕獲當(dāng)前時(shí)刻(3位小數(shù))。在所有版本的Java中,該類能夠以納秒(9個(gè)十進(jìn)制數(shù)字)表示一個(gè)時(shí)刻。但是傳統(tǒng)的計(jì)算機(jī)時(shí)鐘無法如此精細(xì)地精確地跟蹤時(shí)間。ClockInstant
Duration
將已用時(shí)間計(jì)算為持續(xù)時(shí)間對(duì)象。
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
對(duì)于微量標(biāo)記,您可能需要使用系統(tǒng)時(shí)間()。該方法將當(dāng)前時(shí)刻捕獲為自某個(gè)任意起點(diǎn)以來的納秒數(shù)。請(qǐng)注意:根據(jù)任何時(shí)鐘或日歷,此返回的值不代表當(dāng)前時(shí)刻。但它對(duì)于以可能比 更精細(xì)的分辨率跟蹤經(jīng)過的時(shí)間很有用。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: 微床標(biāo)志套件
對(duì)于嚴(yán)肅的基準(zhǔn)測(cè)試,請(qǐng)查看基于JMH的Java 12及更高版本中新增的內(nèi)置基準(zhǔn)測(cè)試框架。參見JEP 230:微板標(biāo)記套件。
添加回答
舉報(bào)