-3

Given the following (which I have taken from a larger program)

t1 = System.currentTimeMillis();
for (int i = 0; i < 3; i++) {
    t2 = System.currentTimeMillis();
    for (int j = i; j <= 1000; j += 3) {
        t3 = System.currentTimeMillis();
        //j loop body
    }  
}

When I run the program and test it for speed, I find that

t2 - t1 is around 2700 milliseconds

t3 - t2 is around 1300 milliseconds

In comparison, the following program prints a time of 3 milliseconds to the console

public class Sum {
    public static void main(String[] args) {
        int sum = 0;
        long t1 = System.currentTimeMillis();
        for (int k = 0; k < 1000000; k++) {
            sum += k;
        }
        System.out.println(System.currentTimeMillis() - t1);
        System.out.println(sum);
    }
}

How can simply entering the i and j for loops take so much time?

I appreciate that I haven't shown the full program for the i and j loops, but if anyone knows of any reason why this might be happening, that would save me creating an appropriate sample program (that isn't too big) to post here.

danger mouse
  • 1,457
  • 1
  • 18
  • 31
  • 3
    Where are you checking `t3 - t2`? Unless it’s inside the first iteration of the inner loop, you’re going to be measuring the entire running time of the loop. – Ry- Jun 06 '15 at 07:28
  • 3
    Worth reading if you haven't done so: http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java – almightyGOSU Jun 06 '15 at 07:28
  • Thanks. I see why now, because I was doing the time comparisons outside of the loops. – danger mouse Jun 06 '15 at 08:40

2 Answers2

1

you set t1 only once, t2 3 times, and t3 around 1000 times.

you compare t1 with the last time you set t2. you compare the last time you set t2 with the last time you set t3.

the first comparison shows you the combined runtime of the inner loops first 2 iterations. the second comparison shows you the runtime of the inner loops 3rd (==last) iteration.

thus your numbers make perfect sense, as the first comparison is about 2 times as large as the second one.

hoijui
  • 3,615
  • 2
  • 33
  • 41
-1

System.currentTimeMillis(); takes a long itme the faster code does not call a function within its for loop

any type of function calling is more work for the cpu than a simple statement or arithmetic operation

Fuad
  • 1,419
  • 1
  • 16
  • 31