How to benchmark methods that throw exceptions?

我的未来我决定 提交于 2019-12-24 00:23:11

问题


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

I tried the following under jmh 1.19:

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

but got this error:

# 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);
    }
}

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


回答1:


Summarizing the answers I've received from I've received from Kiril S. and Oleg Estekhin:

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.



来源:https://stackoverflow.com/questions/45365020/how-to-benchmark-methods-that-throw-exceptions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!