本文介绍了如何对引发异常的方法进行基准测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应该如何对使用jmh引发异常的方法进行基准测试?

How is one supposed to benchmark methods that throw exceptions using jmh?

我在jmh 1.19下尝试了以下方法:

I tried the following under jmh 1.19:

@Benchmark
public void throwException() throws IllegalArgumentException
{
  throw new IllegalArgumentException("Hard-coded exception");
}

但出现此错误:

# Run progress: 0.00% complete, ETA 00:02:00
# Fork: 1 of 3
# Warmup Iteration   1: <failure>

java.lang.IllegalArgumentException: Hard-coded exception
[...]

我应该按如下方式对异常进行黑洞攻击吗?

Am I supposed to blackhole exceptions as follows?

@Benchmark
public void throwException(Blackhole bh)
{
    try
    {
        throw new IllegalArgumentException("Hard-coded exception");
    }
    catch (IllegalArgumentException e)
    {
        bh.consume(e);
    }
}

还是还有另一种方法告诉jmh接受抛出的异常?

or is there another way to tell jmh to accept thrown exceptions?

推荐答案

总结从和 Oleg Estekhin :

如果基准测试方法引发异常,JMH将始终失败.若要更正此问题,基准方法必须捕获异常.然后,它可以使用Blackhole对象使用该异常,或者从基准方法返回该异常.这将防止编译器优化throw语句.

JMH will always fail if a benchmark method throws an exception. To correct this, the benchmark method must catch the exception. It can then consume the exception using a Blackhole object, or return it from the benchmark method. This will prevent the compiler from optimizing-away the throw statement.

这篇关于如何对引发异常的方法进行基准测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 21:38