0

Possible Duplicate:
Java: how much time does an empty loop use?

Take a look at the following:

for (int j = 0 ; j < 5 ; j++) {     
    long t1 = System.currentTimeMillis();
    for (int i = 0 ; i < 10000000 ; i++)
        ; // intentionally empty
    long t2 = System.currentTimeMillis();
    System.out.println (t2 - t1);
}

Output (one of many possible):

2
11
0
0
0

If you run this program multiple times, you will find that the first two numbers of the output are always non-zero while all of the other numbers are indeed 0. Furthermore, the second number usually seems to be higher than the first. This appears to hold even if we loop higher, say until j < 100. Is there any specific reason for this? Of course, milliseconds probably wouldn't make much of a difference in general but I'm just curious.

Community
  • 1
  • 1
arshajii
  • 127,459
  • 24
  • 238
  • 287

3 Answers3

1

The second loop is empty and can be optimized away. Since the JVM needs some time to realize this fact, it isn't done in the beginning. Maybe the time to optimize is spend in the second run.

user unknown
  • 35,537
  • 11
  • 75
  • 121
1

Would this yield the result you are after?

long t1 = System.currentTimeMillis();
for (int j = 0 ; j < 5 ; j++) {     
        for (int i = 0 ; i < 10000000 ; i++){}
        long t2 = System.currentTimeMillis();
        System.out.println(t2 - t1);
    }
zero323
  • 322,348
  • 103
  • 959
  • 935
jonny2k9
  • 166
  • 9
1

The HotSpot JIT does several optimization loops - it first compiles the code into semi-optimized machine version, or even just interprets it. Then it sees that the second loop is in fact a hotspot and recompiles the code with more aggressive optimizations. The compiling process is probably the second peak in performance. Then it executes an optimized version which does nothing so you get all zeroes. If you run the code with -server it might compile the code earlier and you'll get different results. Run it with -Xint to see even performance on each loop iteration.

Denis Tulskiy
  • 19,012
  • 6
  • 50
  • 68