Running a defined loop gives different time everytime

Viewed 50

I have written the below code to observe the timing of a loop function. Surprisingly, It gives me different values for each run.

public static void main(String[] args) {
            for (int attempt = 0; attempt < 10; attempt++) {
            runloop();
        }
    }

    public static void runloop() {
            long sum = 0L;
            long starttime = System.nanoTime();
            for (int x = 0; x < 1000000; x++) {
                sum += x;
            }

            long end = System.nanoTime();
            System.out.println("Time taken:" + (end - starttime) / 1000L);
        }
    }

Observation :

Time taken:4062
Time taken:3122
Time taken:2707
Time taken:2445
Time taken:3575
Time taken:2823
Time taken:2228
Time taken:1816
Time taken:1839
Time taken:1811

I am not able to understand why there is such a difference in the timing. What is the reason ?

1 Answers
Related