A time test for executing a for loop in java

Keywords: jvm

Initially, I used this method of testing a million for loops

public class Main {

    public static void main(String[] args) {
        long start = System.currentTimeMillis();

        for (int j = 0; j < 1000000; j++){
        }
        long stop = System.currentTimeMillis();
        System.out.println(stop - start);
    }
}
image.png

Test results, what???4ms This processor is so fast, my old machine still has a bit of B number in mind, some intelligent compiler or jvm optimized for me, so

public class Main {

    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();

        for (int j = 0; j < 1000000; j++){

            Thread.sleep(0);

        }
        long stop = System.currentTimeMillis();
        System.out.println(stop - start);

    }
}
image.png

Slow down
But after a few tests, it was found that the time was extremely unstable

public class Main {

    public static void main(String[] args) throws InterruptedException {
        long start = 0;
        long stop = 0;
        long sum = 0;
        for (int i = 0; i < 100; i++){
            start = System.currentTimeMillis();
            for (int j = 0; j < 1000000; j++){


                 Thread.sleep(0);

            }
            stop = System.currentTimeMillis();
            sum += (stop - start);
        }
        System.out.println(sum / 100);
    }
ceshi

Tested several times and stayed around 330ms.
330000/1000000
It's about 330 nm in a cycle


Time after the system time is changed to nm

Think about how sleep might involve some thread scheduling issues. That wasn't a waste of a lot of time. There's no use in this way of testing.
Think about it

public class Main {

    public static void main(String[] args) {
        long start = 0;
        long stop = 0;
        long forStart = 0;
        long forStop = 0;
        long forSum = 0;
        long sum = 0;
        for (int i = 0; i < 100; i++){
            start = System.currentTimeMillis();
            for (int j = 0; j < 1000000; j++){
                forStart = System.nanoTime();
                forStop = System.nanoTime();
                forSum += (forStop - forStart);

            }
            stop = System.currentTimeMillis();
            sum += (stop - start);
        }
        System.out.println(sum/100);
        System.out.println(forSum/100000000);
        System.out.println(sum / 100 - forSum /100000000);

    }
}
image.png

[This test is just a play, it doesn't make sense, many factors are not considered]
Knowing what you see in an answer to a time test (so it's still very useful to know the jvm carefully)
https://www.zhihu.com/question/58735131/answer/158460810

Posted by maheshb on Sat, 11 Apr 2020 09:21:11 -0700