Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Total time taken by a loop to complete always different for each execution

Tags:

java

I have a simple below program which iterates through an array

Integer [] intArray = new Integer[20000];
    int index=0;
    for(int i=10000; i>=0; i--){
        intArray[index]=i;
        index++;
    }

    long startTime = System.currentTimeMillis();
    for(Integer t : intArray){

        System.out.println(t);
    }
    long endTime = System.currentTimeMillis();
    long consumedTime = endTime-startTime;
    System.out.println("Consumed time "+ consumedTime);

I always get different values of consumed time like 743, 790, 738, 825, 678.

Why time taken by for loop is always different for each execution.

Note I am running this code inside a main method. My OS is Ubuntu and processor is 32 bit.

like image 884
GD_Java Avatar asked May 27 '13 17:05

GD_Java


2 Answers

Because your program isn't the only thing running on the machine. The OS itself, all the other apps, etc...they take CPU time too -- and not always the exact same amount.

like image 158
cHao Avatar answered Sep 30 '22 08:09

cHao


There is no specific time Java programs will take. It depends what all is running on the machine. Also since you are using Integer it takes more time. If you just native differences will likely be less.

like image 26
fastcodejava Avatar answered Sep 30 '22 08:09

fastcodejava