1 回答

TA贡献1820条经验 获得超3个赞
博士
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:微板标记套件。
添加回答
举报