如何使用 JMH 测量平均冷启动时间?
How to measure average cold start time with JMH?
在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
。
在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
。