javajmh

Java Microbenchmark Harness - how to get the duration of a Benchmark?


Suppose I have

@Benchmark
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void foo() {
    for (int i = 0; i < 1000; i++) {
        System.out.println(i);
    }
}

and it runs, say, in 300 microseconds.

Question: is there any way of obtaining an int/long with the value of 300?


Solution

  • You can run the benchmark programatically and access its result:

    public class BenchmarkRunner {
    
      public static void main(String[] args) throws Exception {
        Options opt = new OptionsBuilder()
                .include(YourBenchmark.class.getSimpleName())
                .warmupIterations(10)
                .warmupTime(TimeValue.seconds(1))
                .measurementIterations(10)
                .measurementTime(TimeValue.seconds(2))
                .forks(5)
                .shouldFailOnError(true)
                .build();
    
        Collection<RunResult> runResults = new Runner(opt).run();
        runResults.forEach(runResult -> {
          Result primaryResult = runResult.getPrimaryResult();
          double score = primaryResult.getScore(); // <-- here's the score of your benchmark
        });
      }
    }