Best way of stopping java optimising away a method call when performance testing
Im doing some performance optimising on some code, and I've got two ways of doing a calculation.
I've got a simple test harness:
long start, end;
long oldDuration, newDuration;
int answer;
final int TEST_COUNT = 1000;
start = System.currentTimeMillis();
for(int i = 0 ; i < TEST_COUNT; i++)
开发者_如何学C {
answer = doCaluculationNewWay()
}
end = System.currentTimeMillis();
newDuration = end - start;
start = System.currentTimeMillis();
for(int i = 0 ; i < TEST_COUNT; i++)
{
answer = doCaluculationOldWay()
}
end = System.currentTimeMillis();
oldDuration = end - start;
How can I be sure that the JVM isnt just binning the call, knowing that the answer isnt being used?
I considered making answer volatile, but Im worried that it will impose an additional performance overhead due to memory synching issues.
Add answer
to some sum
variable and, on test's exit, print that sum.
Simply keep adding the result to your dummy result variable, i.e.
answer += doCaluculationNewWay()
Then print the end result to the console - then even the most aggressively optimizing JIT should consider the results to be actually used.
And if that addition has any impact at all on the total running time, then I very much doubt you should be worried about the performance in the first place.
If you are trying to do a microbenchmark, be careful. In addition to what the guys said above (keep track of the total and print it), be sure to use the right tool. Something like Google Caliper is good for micro benchmarks.
精彩评论