猿问

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

我有一段这样的代码:


    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


任何帮助将不胜感激=)


LEATH
浏览 132回答 1
1回答

DIEA

博士Duration.between(&nbsp; &nbsp; &nbsp; &nbsp;// Represent a span-of-time as a count of nanoseconds, to be calculated as hours-minutes-seconds.&nbsp; &nbsp; then ,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Earlier in your code, capture the previous current moment: `Instant then = Instant.now() ;`&nbsp; &nbsp; Instant.now()&nbsp; &nbsp; &nbsp; &nbsp;// Capture the current moment.&nbsp;)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Returns a `Duration` object, our elapsed time..toNanos()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Get the total number of nanoseconds in the entire span-of-time. Returns a `long`.&nbsp;捕捉当前时刻您的代码正在捕获当前时刻,快照,冻结。生成的对象不会更新。这就是短语“特定时刻”在 JavaDoc 类中的含义。若要跟踪经过的时间,必须捕获当前时刻两次,从而生成两个单独的对象。避免使用传统的日期时间类这个类很糟糕,几年前被Java.time类所取代,采用了JSR 310。具体来说,替换 ,通常实现 。CalendarZonedDateTimeGregorianCalendarCalendarInstant跟踪当前时刻的现代方法使用类。表示 UTC 中的某个时刻。InstantInstantInstant start = Instant.now() ;…&nbsp; // Do some stuff.Instant stop = Instant.now() ;分辨率在 Java 9 及更高版本中,当前时刻以微秒(小数秒的 6 位小数点)的分辨率捕获。在Java 8中,较早的即时实现仅限于以毫秒为单位捕获当前时刻(3位小数)。在所有版本的Java中,该类能够以纳秒(9个十进制数字)表示一个时刻。但是传统的计算机时钟无法如此精细地精确地跟踪时间。ClockInstantDuration将已用时间计算为持续时间对象。Duration duration = Duration.between( start , stop ) ;&nbsp; // Represents a span of time in terms of hours-minutes-seconds.long nanoseconds = duration.toNanos() ;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Converts this duration to the total length in nanoseconds expressed as a long.System.nanoTime对于微量标记,您可能需要使用系统时间()。该方法将当前时刻捕获为自某个任意起点以来的纳秒数。请注意:根据任何时钟或日历,此返回的值不代表当前时刻。但它对于以可能比 更精细的分辨率跟踪经过的时间很有用。Instantlong start = System.nanoTime() ;&nbsp; // Some arbitrarily defined count of nanoseconds. *NOT* the current time/date by any clock/calendar.&nbsp;…&nbsp; // Do some stuff.long stop = System.nanoTime() ;long nanoseconds = ( stop - start ) ;JEP 230: 微床标志套件对于严肃的基准测试,请查看基于JMH的Java 12及更高版本中新增的内置基准测试框架。参见JEP 230:微板标记套件。
随时随地看视频慕课网APP

相关分类

Java
我要回答