关于Java中System.currentTimeMillis和System.nanoTime的错误认识

在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提供了纳秒级别的精度,但实际上获得的值可能没有精确到纳秒。

但总的来说,这两个函数的用途是完全不一样的!

你可能感兴趣的:(关于Java中System.currentTimeMillis和System.nanoTime的错误认识)