在 JMH(Java Microbenchmark Harness)中,我们可以使用
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 10)
@Measurement(iterations = 10)
评估 JVM 预热后执行的平均时间。我们也可以使用
@BenchmarkMode(Mode.SingleShotTime)
@Measurement(iterations = 1)
估计执行的冷启动时间。但这只会执行一次基准测试,这可能会引入偏差。那么有没有什么方法可以评估JMH中冷启动的平均时间呢?
最佳答案
根据 Alexey himself (虽然从 2014 年开始):
Single-shot benchmarks were originally destined to run a single measurement iteration over multiple forks -- the scenarios to estimate "cold" performance. But for many cases, you might want more measurement iterations there especially if you are running only a single fork, because more samples would be generated.
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class AverageSingleShot {
public static void main(String[] args) throws Exception {
Options opt = new OptionsBuilder()
.include(AverageSingleShot.class.getSimpleName())
.build();
new Runner(opt).run();
}
@Fork(100)
@Benchmark
@BenchmarkMode(Mode.SingleShotTime)
public int test() {
return ThreadLocalRandom.current().nextInt() + ThreadLocalRandom.current().nextInt();
}
}
除了这会告诉你平均值的事实(参见 100
): Benchmark Mode Cnt Score Error Units
AverageSingleShot.test ss 100 41173.540 ± 2871.546 ns/op
您还将获得 Percentiles
和一个 Histogram
.
关于java - 如何使用 JMH 测量平均冷启动时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65142842/