0

I tried to implement a counter using Java 8's LocalTime and Instant, both works fine but the output is a bit confusing! when ever I use Instant I got smaller values for the same loop ? any idea?

// using Instant 
Instant before=Instant.now();
// something time consuming
for(int i=1;i<100000000;i++);
Instant after=Instant.now();
Duration duration=Duration.between(before, after);
System.out.println(duration.toMillis());


// using LocalTime
LocalTime xBefore=LocalTime.now();
for(int i=1;i<100000000;i++);
LocalTime yAfter=LocalTime.now();
System.out.println(ChronoUnit.MILLIS.between(xBefore, yAfter));
  • Thanks for mentioning that Holger! –  Sep 13 '17 at 08:07
  • 1
    There is a significant difference between *elapsed time* and the real world (“wall clock”) time, as the system clock might be subject to NTP corrections and such alike. If you want to measure the *elapsed time*, use [`System.nanoTime()`](https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#nanoTime--) and calculate the difference. But it’s normal that the execution time decreases as the JVM’s optimizer does its work. You can read more in the linked Q&A… – Holger Sep 13 '17 at 08:08

1 Answers1

0

If I understand you correctly, you want to time the for loop (which does nothing) in different ways.

It is quite likely that this for loop is completely optimized away so that the time it uses decreases.

glglgl
  • 89,107
  • 13
  • 149
  • 217