简体   繁体   中英

Testing void methods with JMH

I'm testing bunch of void methods with JMH. I know the importance of using blackhole to prevent dead code elimination. But what about void methods? I cannot consume them with blackholes, will they be properly tested?

If your method accepts any parameters you could try this:

@Benchmark
public Object test() {
  yourVoidMethod(param);
  return param;
}

Compiler might think that param is somehow modified within tested method and won't throw the code away.

Also for some void methods you can do smth like:

@Benchmark
public int test() {
  yourVoidMethod();
  return hashCode();
}

For me it worked for cases like

@Benchmark
public int sleep() {
  while (run) {
    LockSupport.parkNanos(TimeUnit.MICROSECONDS.toNanos(pause));
  }
  return hashCode();
}

but this is quite a special case.

The best approach is to redesign your code in a way to return something from it.

UPD : You could also try to extend from the class encapsulating your code in order to somehow use Blackhole inside of your code, eg via overriding or overloading a method. See https://github.com/openjdk/jmh/blob/master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_28_BlackholeHelpers.java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM