java中獲取比毫秒更為精確的時間


所以這里提醒做非常精確的時間統計的朋友,謹慎使用System.currentTimeMillis() 。

 

在Java中可以通過System.currentTimeMillis()或者System.nanoTime() (JDK>=5.0) 方法獲得當前的時間的精確值。但是通過閱讀Javadoc,我們發現這兩個方法並不一定保證得到你所期望的精度。先來看 System.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.

 

JDK5.0加入的System.nanoTime()方法。Javadoc對該方法的描述如下:

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.

它返回系統能夠提供的最為精確的計時,以納秒(10億分之一秒)為單位,但並不保證納秒級精度。

 

如果你的Java程序需要高精度的計時,如1毫秒或者更小,使用System.nanoTime()方法,它完全可以滿足你的需求。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM