在 Java 中要獲取時間有兩種方式,分別是
System.currentTimeMillis()
與 System.nanoTime()
首先先來看 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.
從上面敘述可以發現其返回值是依賴於底層作業系統
精確度為毫秒但不保證為 1 毫秒
而其返回的數字就是自 1970 年 1 月 1 日 0 點到現在所經過的時間
System.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.
其返回系統能夠提供的最為精確的計時
以奈秒(10億分之一秒)為單位但不保證為奈秒級
也就說計數自程式開始起到呼叫此涵式後所計數的時間
故要獲取返回值為奈秒的現在時刻需要用這兩個涵式來搭配