But what about the results? The compiler sees that it is no longer in use and does not make the call (but can it see any side effects that the method call may have?)
It depends. If the JIT compiler can detect that a method call has no side effects, it has the right to optimize it. Moreover, the value of the result is not used. In this case, you can simply measure calls to random.nextDouble() ... or, possibly, to an empty loop.
To be sure that it cannot be optimized, you should probably write it as follows:
int numValues = 1000000; Random random = new Random(); startMeasuringTime(); double result; for (int i = 0; i < numValues; i++) { result = result + calculatorInstance.doSomeCalculationsOn(random.nextDouble()); } stopMeasuringTime(); System.err.println(result);
(I assume that calculating the time takes dependent on the argument ...)
You also need to consider the JVM workout; those. run this control code several times in the JVM until the measured time has stabilized.
Saying that the compiler is "too optimized" is wrong. The compiler really does its job correctly. In any case, an error in the code; that is, "nothing useful."
Stephen c
source share