问题
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