Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is System.nanoTime() incorrect in the beginning of iterations?

Tags:

java

loops

time

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:

Test result 1

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:

Test result 2

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.

like image 833
Robin Avatar asked Feb 11 '23 21:02

Robin


1 Answers

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!

like image 115
Brian Agnew Avatar answered Feb 13 '23 22:02

Brian Agnew