I am doing some simple tests with double, like this:
startTime = System.currentTimeMillis();
for (int i = 0; i < 100_000_000; i++)
{
doubleCalcTest();
}
endTime = System.currentTimeMillis();
System.out.println("That took " + (endTime - startTime) + " nanoseconds");
.
public static double doubleCalcTest()
{
double x = 987.654321;
double y = 123.456789;
x = x + y;
x = x - y;
x = x * y;
return x / y;
}
It turns out that the output is 0 milliseconds. It doesn’t make sense to me because if I set the for loop to run only for 100,000 times, the output is 3 milliseconds.
I found int also acting in the same way.
Can anyone give me a hand on this one? Thanks.
I changed my code to call ‘System.nanoTime’ time and passing in a double value incremented by the index of the loop as suggested.
double x = 123.456789
startTime = System.nanoTime();
for (int i = 0; i < 100_000_000; i++)
{
x = x + i;
doubleCalcTest(x);
}
endTime = System.nanoTime();
System.out.println("That took " + (endTime - startTime) + " nanoseconds");
.
public static double doubleCalcTest(double x)
{
double y = 123.456789;
x = x + y;
x = x - y;
x = x * y;
return x / y;
}
Run 10,000 times took 503,200 nanoseconds
Run 10,000,000 times took 3,421 nanoseconds
The JIT discards the execution of
DoubleCalcTestsince it does not have any side-effect (pure calculation) and the result is not used. The loop itself can also be optimized out since there is no effect.Try this with JIT off and it will take around 8000 ms:
At the byteocde level, nothing is optimized out.
result:
If you try to use to result of DoubleCalc() by assigning it to a variable and print it afterward.
It will take the same time. Why? The JIT seems to be smart enough to understand that the result does not depend on the number of time the iteration is done.
However, if you change this to:
The result depends on the number of iteration and the JIT does not optimize further. In this case, it takes about 100 ms. If I change 100000000 for 200000000, it takes twice as much time.
So the conclusion is that the JIT stops there.
NOTE:
For the give C program:
GCC is able to optimized the loop entirely and compute the value of x at compile-time:
main.s:
Pretty cool, heh?