为了账号安全,请及时绑定邮箱和手机立即绑定

Java 日历 getTime在千里() 返回同一时间

Java 日历 getTime在千里() 返回同一时间

LEATH 2022-09-14 16:04:59
我有一段这样的代码:    Calendar c = Calendar.getInstance();    long startTime = c.getTimeInMillis();    while (x < 10000000) {//check all the integers from 1 to 10000000 to                          //to see if they're prime or not}    long endTime = c.getTimeInMillis();    long totalTime = endTime - startTime;该循环肯定运行1000万次,并且包含不同的值。startTimeendTime但是,始终等于 0。totalTime为什么 和 包含相同的值?startTimeendTime任何帮助将不胜感激=)
查看完整描述

1 回答

?
DIEA

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:微板标记套件。


查看完整回答
反对 回复 2022-09-14
  • 1 回答
  • 0 关注
  • 131 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号