Skip to content

Instantly share code, notes, and snippets.

@ratcashdev
Created October 29, 2019 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ratcashdev/23943db9610ddca50d05807a5c18f17c to your computer and use it in GitHub Desktop.
Save ratcashdev/23943db9610ddca50d05807a5c18f17c to your computer and use it in GitHub Desktop.
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