【发布时间】:2018-04-16 05:57:45
【问题描述】:
受another question on Stack Overflow的启发,我写了一个微基准来检查,什么效率更高:
- 有条件地检查零除数或
- 捕获和处理
ArithmeticException
下面是我的代码:
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class MyBenchmark {
private int a = 10;
// a little bit less obvious than int b = 0;
private int b = (int) Math.floor(Math.random());
@Benchmark
public float conditional() {
if (b == 0) {
return 0;
} else {
return a / b;
}
}
@Benchmark
public float exceptional() {
try {
return a / b;
} catch (ArithmeticException aex) {
return 0;
}
}
}
我对 JMH 完全陌生,不确定代码是否正常。
我的基准测试是否正确?你发现有什么错误吗?
旁白:请不要建议在https://codereview.stackexchange.com 上提问。对于 Codereview 代码必须已经按预期工作。我不确定这个基准是否能按预期工作。
【问题讨论】:
标签: java microbenchmark jmh