Search code examples
javabenchmarkingjmh

How to retrieve benchmark JMH result as Java object after execution?


I have a project in which I wrote a benchmark function with JMH library :

  @Benchmark
  @Fork(value = 2, warmups = 1)
  @Measurement(iterations = 3, time = 5)
  @Warmup(iterations = 2, time = 5)
  @BenchmarkMode(Mode.AverageTime)
  public Collection<List<String>> benchmark(final MyState myState) {
    return myState.field.execute();
  }

I launch this benchmark with

  public static void main(final String[] args) throws RunnerException {
    final Options options = new OptionsBuilder().build();
    new Runner(options).run();
  }

I would like to retrieve the benchmark result as a Java object (BenchmarkTaskResult for example).

One solution would be to output the result as a json like this :

  public static void main(final String[] args) throws RunnerException {
    final Options options =
        new OptionsBuilder().result(result.json).resultFormat(ResultFormatType.JSON).build();
    new Runner(options).run();
  }

And then deserialize the json file to put it in a Java object.

Is there a way to retrieve the benchmark result directly in a Java object without having to deserialise anything ?


Solution

  • You can try something like

    final Options options = new OptionsBuilder().build();
    Collection<RunResult> runResults = new Runner(options).run();
    runResults.forEach(runResult -> {
      BenchmarkResult aggregatedResult = runResult.getAggregatedResult();
      Result primaryResult = runResult.getPrimaryResult();
      // ...
    });