關於Java中System.currentTimeMillis和System.nanoTime的錯誤認識

來源:互聯網
上載者:User

在Java裡面,時間戳記常用System.currentTimeMillis(),因為它可以方便地與Date/Calendar進行轉 換,System.nanoTime到不是怎麼常用(至少我沒怎麼用過)。剛才在學習Java的線程池中的 ScheduledThreadPoolExecutor時,看到裡面很多地方都用到了它,於是好奇地看了下API。

 

currentTimeMillis
public static long currentTimeMillis()
Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

See the description of the class Date for a discussion of slight discrepancies that may arise between "computer time" and coordinated universal time (UTC).

Returns:
the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.

 

nanoTime
public static long nanoTime()
Returns the current value of the most precise available system timer, in nanoseconds.

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.

For example, to measure how long some code takes to execute:

 long startTime = System.nanoTime(); // ... the code being measured ... long estimatedTime = System.nanoTime() - startTime; 
Returns:
The current value of the system timer, in nanoseconds.
Since:
1.5

 

原以為,nanoTime是比millisTime更精確的時間描述而已,但看了上面的說明,才發現這個認識基本上是完全錯了。

首 先,currentTimeMills返回的結果,是自1970-1-1UTC到目前時間為止的,以毫秒為單位的時間,這是沒有什麼爭意的。但是,nanoTime而返回的可能是任意時間,甚至可能是負數……按照API的說明,nanoTime主要的用途是衡量一個時間段,比如說一段代碼執行所 用的時間,擷取資料庫連接所用的時間,網路訪問所用的時間等。另外,nanoTime提供了納秒層級的精度,但實際上獲得的值可能沒有精確到納秒。

但總的來說,這兩個函數的用途是完全不一樣的!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.