我写了两个基准来证明JIT可能是编写精细基准测试的问题(请跳过我在这里不使用@State):
@Fork(value = 1)
@Warmup(iterations = 2, time = 10)
@Measurement(iterations = 3, time = 2)
@BenchmarkMode(Mode.AverageTime)
public class DeadCodeTraps {
@Benchmark
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public static void summaryStatistics_standardDeviationForFourNumbers() {
final SummaryStatistics summaryStatistics = new SummaryStatistics();
summaryStatistics.addValue(10.0);
summaryStatistics.addValue(20.0);
summaryStatistics.addValue(30.0);
summaryStatistics.addValue(40.0);
summaryStatistics.getStandardDeviation();
}
@Benchmark
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public static void summaryStatistics_standardDeviationForTenNumbers() {
final SummaryStatistics summaryStatistics = new SummaryStatistics();
summaryStatistics.addValue(10.0);
summaryStatistics.addValue(20.0);
summaryStatistics.addValue(30.0);
summaryStatistics.addValue(40.0);
summaryStatistics.addValue(50.0);
summaryStatistics.addValue(60.0);
summaryStatistics.addValue(70.0);
summaryStatistics.addValue(80.0);
summaryStatistics.addValue(90.0);
summaryStatistics.addValue(100.0);
summaryStatistics.getStandardDeviation();
}
}
我认为JIT将消除死代码,因此两个方法将同时执行.但最后,我有:
summaryStatistics_standardDeviationForFourNumbers 0.158±0.046
DeadCodeTraps.summaryStatistics_standardDeviationForTenNumbers 0.359±0.294
为什么JIT不优化它? summaryStatistics.getStandardDeviation()的结果;在方法之外的任何地方都不使用它,它不会被返回.
(我使用的是OpenJDK build 10.0.2 13-Ubuntu-1ubuntu0.18.04.4)