5

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.

GD_Java
  • 1,359
  • 6
  • 24
  • 42
  • 1
    Example of things that can go wrong when measuring the time taken by a piece of Java code: http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java – assylias May 27 '13 at 17:20

5 Answers5

4

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.

cHao
  • 84,970
  • 20
  • 145
  • 172
2

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.

fastcodejava
  • 39,895
  • 28
  • 133
  • 186
1

This is because your operating system switches tasks and performs gazillions of simultaneous operations as you are running your java program. Your program can be fast if the OS is not processing a lot by the time you ran it, and it can also be slow when the OS is busy.

In other words, the operating system is performing a different set of concurrent tasks every time your program runs thus, different execution times.

0

Because Java makes no promises about execution time. In a modern OS there are lots of things going on at once.

Even though the times are not the same I don't see much variation.

carej
  • 596
  • 1
  • 6
  • 18
0

Profiling a Java program reliably is far from trivial. Besides the variations caused by other processes on your machine doing their stuff, already pointed out in the other answers, you also get nondeterminism due to garbage collection and interesting effects of your virtual machine, if it has a Just-In-Time compiler.

In your example, garbage collection isn't really an issue, but JIT compilation may very well cause the first few loop iterations to be significantly slower than the next couple of thousand. It is therefore wrong to divide the total time by the number of iterations to get a good approximation of the average time per iteration.

In order to avoid this effect, you have to "exercise" the loop body a number of times before you start measuring.

Arend
  • 2,363
  • 1
  • 18
  • 18