3

I just had nothing to do and started messing around with for loops in Java, so I wrote the following function

static int getCurrentTime() {
    return (int)System.currentTimeMillis();
}

which simply gets the time for me.

Now I have my main function:

public static void main(String[] args) {
    int s = 0;
    int beginTime = getCurrentTime();
    for (int j = 0; j < 2000000000; ++j)
        for (int i = 0; i < ####; ++i)
            s++;

    System.out.println("done in " + (getCurrentTime() - beginTime)+
                       " milliseconds!");
}

Now when I put 1 in the place of ####, I get the following output

done in 4118 milliseconds!

But when I put 3 in the place of ####, I get the following output

done in 11 milliseconds!

How is this possible? How did more iterations take less time? I'm really confused about what's happening here.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mahmoodsheikh36
  • 129
  • 1
  • 6
  • 2
    Since you do not use `s` variable JIT may have decided to completely remove your both for-loops. JIT is very smart and can simply eliminate such code. Microbenchmarking in Java is **really** non-trivial: https://www.baeldung.com/java-microbenchmark-harness – Ivan Dec 27 '18 at 21:14
  • @Ivan I've just tested that theory and, even after using `s`, I'm still seeing this. – Joe C Dec 27 '18 at 21:16
  • You are measuring the time it takes for the JVM to detect the code doesn't do anything and do a code replacement for that. How long this takes can vary significantly between runs and based on a number of factors which don't matter for most real programs. – Peter Lawrey Dec 27 '18 at 21:39
  • Using JMH it shows 10E-10 seconds per method (Warmup Iteration 2: ˜ 10?¹° s/op) which basically confirms that JIT eliminated that loop completely – Ivan Dec 27 '18 at 21:41

0 Answers0