访问 JMH 状态

Accessing JMH state

我正在为我的应用程序设置 JMH 基准,我想知道通过基准传递 JMH 状态和从基准主体访问它之间有什么区别吗?

换句话说

@Benchmark
public int myBenchmark(MyState state) {
MyObject objFromState= state.objFromState;
return objFromState.benchmarkMe();
}

VS

@Benchmark
public int myBenchmark() {
return objFromState.benchmarkMe();
}

来自official JMH samples

... Since JMH is heavily used to build concurrent benchmarks, we opted for an explicit notion of state-bearing objects ... Benchmark methods can reference the states, and JMH will inject the appropriate states while calling these methods.

我看到的所有样本总是以与代码段中相同的方式引用状态:

  @State(Scope.Thread)
  public static class ThreadState {
      volatile double x = Math.PI;
  }

  @Benchmark
  public void measureUnshared(ThreadState state) {
    state.x++;
  }

您必须指定状态的范围,使用注释显式声明它 - 您可以通过这样做来“注册”它。状态对象将进一步注入到引用它的方法(通过将依赖项声明为方法参数)。在您的第二个片段中,您引用了 state 对象 - 是的,但这不是共享状态。