I've noticed a pattern with System.nanoTime(). Everytime I begin an iteration, the nanoTime() gets hugely incorrect for a couple of laps until it finally stabilises.
If I for instance run the following code:
public class TimeTest{
public static void main(String[] args) {
long prev = System.nanoTime();
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 1000000; j++);
long time = System.nanoTime();
System.out.println(time - prev);
prev = time;
}
}
}
I get the following result:
To eliminate the possibility of System.out.println(String) messing with the result, I can also run the following test:
public class TimeTest{
public static void main(String[] args) {
long[] difs = new long[10];
long prev = System.nanoTime();
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 1000000; j++);
long time = System.nanoTime();
difs[i] = (time - prev);
prev = time;
}
for(long l : difs)
System.out.println(l);
}
}
Which gives the following result:
The initial delay could possibly be explained by assuming that the beginning of an iteration (in this case the for-loop) is taking some extra time to initialize before the loop begins. However, since the second lap supposedly also takes a long time to execute, we can believe that it might not be the for-loop after all.
So my question is simply, what is causing this initial delay when using System.nanoTime() together with iterations?
Note: I've also tried different types of iterators, but the problem remains.
That looks to me like the JIT warm up time of the JVM
The Java HotSpot compiler kicks in when it sees a ‘hot spot’ in your code. It is therefore quite common that your code will run faster over time! So, you should adapt your testing methods.
The HotSpot compiler compiles in the background, eating away CPU cycles. So when the compiler is busy, your program is temporarily slower. But after compiling some hot spots, your program will suddenly run faster!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With