简体   繁体   English

使用 JMH 测试 void 方法

[英]Testing void methods with JMH

I'm testing bunch of void methods with JMH.我正在用 JMH 测试一堆 void 方法。 I know the importance of using blackhole to prevent dead code elimination.我知道使用黑洞来防止死代码消除的重要性。 But what about void methods?但是 void 方法呢? 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.编译器可能会认为param在测试方法中以某种方式进行了修改,并且不会丢弃代码。

Also for some void methods you can do smth like:此外,对于一些 void 方法,您可以执行以下操作:

@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. UPD :您还可以尝试从封装您的代码的 class 扩展,以便以某种方式在您的代码中使用Blackhole ,例如通过覆盖或重载方法。 See https://github.com/openjdk/jmh/blob/master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_28_BlackholeHelpers.javahttps://github.com/openjdk/jmh/blob/master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_28_BlackholeHelpers.Z93F725A07423FE1C889F448B33D21F46

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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