JMH是否有类似JUnit AssumptionViolatedException的机制跳过无效参数组合的基准测试?
JMH中跳过无效参数组合的实现方案
JMH支持跳过无效的参数组合,无需自定义异常,直接用现成机制就能实现类似JUnit AssumptionViolatedException的效果——跳过执行且不标记为失败。
方法一:用JUnit的AssumptionViolatedException(推荐)
如果项目已依赖JUnit,直接在@Setup方法中抛出这个异常即可,JMH会自动识别并跳过当前参数组合的所有测试步骤。
修改后的示例代码:
import org.junit.AssumptionViolatedException; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; @State(Scope.Benchmark) public class JMHBenchmark { @Param({"s1", "s2"}) String param1; @Param({"s3", "s4"}) String param2; @Setup public void setup() { if (param1.equals("s1") && param2.equals("s4")) { // 标记该参数组合无效,直接跳过 throw new AssumptionViolatedException("Skip invalid combination: s1 + s4"); } // 正常的基准测试初始化逻辑 } // 你的基准测试方法 // @Benchmark // public void executeBenchmark() { // // 业务逻辑代码 // } }
方法二:JMH原生控制(无JUnit依赖)
如果不想引入JUnit,可以借助Control类在基准测试方法中主动停止无效实例的测量:
import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Control; @State(Scope.Benchmark) public class JMHBenchmark { @Param({"s1", "s2"}) String param1; @Param({"s3", "s4"}) String param2; private boolean isCombinationValid; @Setup public void setup() { // 标记参数组合是否有效 isCombinationValid = !(param1.equals("s1") && param2.equals("s4")); if (isCombinationValid) { // 仅在组合有效时执行初始化 // ... } } @Benchmark public void executeBenchmark(Control control) { if (!isCombinationValid) { // 停止当前参数组合的测量 control.stopMeasurement(); return; } // 基准测试核心逻辑 } }
关键提示
- 不要自定义异常(比如你示例中的
DoNotBenchmarkException),JMH不会识别这类异常,会直接判定为测试失败。 - 第一种方法更简洁,完全匹配你想要的"跳过无效组合且不报错"的需求,优先推荐。
内容的提问来源于stack exchange,提问作者thecoop
相关产品推荐
相关产品推荐

