nok*_*kul 8 java testing performance
我有一个类,它做了一些耗时的计算.我正在尝试对它进行性能测试:
int numValues = 1000000;
Random random = new Random();
startMeasuringTime();
double result;
for (int i = 0; i < numValues; i++) {
result = calculatorInstance.doSomeTimeConsumingCalculationsOn(random.nextDouble());
}
stopMeasuringTime();
Run Code Online (Sandbox Code Playgroud)
我正在使用随机值,因此编译器不会将计算优化为相同的百万倍.但结果怎么样?编译器是否看到它不再被使用并且省略了调用(但是,它可以看到方法调用可能产生的任何副作用吗?)
我不想把结果放在某个地方(放入文件,数组或System.out),因为我认为这会减慢我不想测量的工作的速度.或者产生OutOfMemoryError.
提前致谢.
编辑:改变了标题
但结果怎么样?编译器是否看到它不再被使用并且省略了调用(但是,它可以看到方法调用可能产生的任何副作用吗?)
这取决于.如果JIT编译器可以检测到方法调用没有副作用,那么它有权对其进行优化.特别是因为没有使用结果值.在这种情况下,您可能只是测量对random.nextDouble()... 的调用或可能是空循环.
为了确保你不应该优化它,你应该写这样:
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); // Force result to be computed.
Run Code Online (Sandbox Code Playgroud)
(我假设耗时的计算确实取决于参数......)
您还需要考虑JVM热身; 即在JVM中多次运行该基准代码,直到测量的时间稳定为止.
说编译器"过度优化"是错误的.编译器实际上正确地完成了它的工作.如果有的话,错误就在你的代码中; 即它"没有用".
| 归档时间: |
|
| 查看次数: |
469 次 |
| 最近记录: |