受 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,代码必须已经按预期工作。我不确定这个基准测试是否按预期工作。
int
参数来确定百分比,相应地填充一个数组,然后在设置中对其进行洗牌。在基准测试中,我要么循环遍历数组,要么在每一步上计算index = (index+1) & array.length-1
(使用长度为2的幂的数组)。你可以跳过第2和第3点,因为它们是特殊情况。 - maaartinus