Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JMH benchmark to compare conditional and bitwise AND
package alu.vs.branch;
import java.util.Random;
import org.agrona.BitUtil;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.CompilerControl;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
public class ConditionalAndBenchmark {
public static final byte[] PREFERRED_ASF_BYTES = BitUtil.fromHex("CFEEBFAA");
@State(Scope.Benchmark)
public static class BenchmarkState {
int[] inputs;
@Param({"32", "128", "512", "4096"})
private int inputSize;
private int mask;
private int indx = 0;
private Random r = new Random();
public BenchmarkState() {
inputs = new int[4096];
for (int i = 0; i < 4096; i++) {
inputs[i] = r.nextInt(Integer.MAX_VALUE);
}
}
@Setup(Level.Trial)
public void doSetup() {
mask = inputSize - 1;
indx = 0;
}
public int getInput() {
final int current = indx;
indx = (indx + 1) & mask;
return inputs[current];
// return r.nextInt(Integer.MAX_VALUE);
}
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
@CompilerControl(CompilerControl.Mode.DONT_INLINE)
public boolean testConditionalAnd(BenchmarkState state) {
final int value = state.getInput();
return (byte) (value >>> 24) == PREFERRED_ASF_BYTES[0]
&& (byte) (value >>> 16) == PREFERRED_ASF_BYTES[1]
&& (byte) (value >>> 8) == PREFERRED_ASF_BYTES[2]
&& (byte) value == PREFERRED_ASF_BYTES[3];
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
@CompilerControl(CompilerControl.Mode.DONT_INLINE)
public boolean testLogicalAnd(BenchmarkState state) {
final int value = state.getInput();
return (byte) (value >>> 24) == PREFERRED_ASF_BYTES[0]
& (byte) (value >>> 16) == PREFERRED_ASF_BYTES[1]
& (byte) (value >>> 8) == PREFERRED_ASF_BYTES[2]
& (byte) value == PREFERRED_ASF_BYTES[3];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.