How to consume primitive values in a loop?
Aleksey Shipilev
shade at redhat.com
Tue Feb 20 16:11:38 UTC 2018
On 02/20/2018 05:08 PM, Roman Leventov wrote:
> When the body of a benchmark contains a loop (I
> see JMHSample_11_Loops.java, but sometimes... often... loop is needed)
> What is the better way to consume primitives, produced in the loop?
>
> 1) Summing (XORing) them and consume (or return) the dummy value after the
> loop:
>
> @Benchmark
> public long someBench() {
> int sum = 0;
> for (...) {
> sum += someValue();
> }
> return sum;
> }
>
> 2) Calling blackhole.comsume() on each iteration:
>
> @Benchmark
> public void someBench(Blackhole bh) {
> for (...) {
> bh.consume(someValue());
> }
> }
>
> My concern about the second option is that bh.consume() may skew the
> results, because the production loop doesn't contain this (potentially
> costly) call.
It really depends on what you are trying to measure. Does the real code has the loop over values and
accumulates the result? You should do the same. Does it call the function on different values in
different places? You should do the same.
See also:
http://hg.openjdk.java.net/code-tools/jmh/file/25d8b2695bac/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_34_SafeLooping.java
-Aleksey
More information about the jmh-dev
mailing list