亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java 日歷 getTime在千里() 返回同一時間

Java 日歷 getTime在千里() 返回同一時間

LEATH 2022-09-14 16:04:59
我有一段這樣的代碼:    Calendar c = Calendar.getInstance();    long startTime = c.getTimeInMillis();    while (x < 10000000) {//check all the integers from 1 to 10000000 to                          //to see if they're prime or not}    long endTime = c.getTimeInMillis();    long totalTime = endTime - startTime;該循環肯定運行1000萬次,并且包含不同的值。startTimeendTime但是,始終等于 0。totalTime為什么 和 包含相同的值?startTimeendTime任何幫助將不勝感激=)
查看完整描述

1 回答

?
DIEA

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:微板標記套件。


查看完整回答
反對 回復 2022-09-14
  • 1 回答
  • 0 關注
  • 117 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號