如何在 JMH 中为不同的测试设置不同的初始化(设置)方法?

How do I have different initialization (setup) methods for different tests in JMH?

我正在编写一个 JMH 测试来比较两个不同的实现。所以我有类似的东西:

Counter c1;
Counter c2;

@Setup
public void setup() {
    c1 = new Counter1();
   c2 = new Counter2();
}

@Benchmark
public int measure_1_c1() {
    return measure(c1);
}

@Benchmark
public int measure_2_c2() {
    return measure(c2);
}

每个测试都会 运行 在它自己的分支 JVM 中。问题是每个操作都需要在构造函数中进行大量设置(当时我有大约 20 个)。因此,我想在我的 @Setup 方法中做的是仅初始化将根据此分叉 JVM 中的测试 运行 使用的方法。

有办法吗?

是的,您需要单独的 @State 对象并根据需要引用它们。例如:

@State
public static class State1 {
    int x;

    @Setup
    void setup() { ... }
}

@State
public static class State2 {
    int y;

    @Setup
    void setup() { ... }
}

@Benchmark
public int measure_1(State1 s1) {
    // Only s1 @Setup have run
    // use s1.x...
}

@Benchmark
public int measure_2(State2 s2) {
    // Only s2 @Setup have run
    // use s2.y...
}

@Benchmark
public int measure_3(State1 s1, State2 s2) {
    // s1 and s2 @Setups have run
    // use s1.x, s2.y...
}