Java – why system Nanotime() is incorrect at the beginning of the iteration?

I noticed system The mode of nanotime() Whenever I start an iteration, nanotime () becomes very incorrect in a few laps until it finally stabilizes

For example, if I 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 got the following results:

To eliminate system out. Println (string) is the possibility of confusing the results. I can also run the following tests:

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);
    }
}

This gives the following results:

The initial delay can be explained by assuming that the start of the iteration (in this case, the for loop) takes some additional time to initialize before the start of the loop However, since the second lap is said to take a long time to execute, we can believe that it is not for loop after all

So my question is very simple when using system What is the reason for this initial delay during nanotime () and iteration?

Note: I've tried different types of iterators, but the problem still exists

Solution

This looks like JIT warm up time of the JVM

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>