Skip to content

Instantly share code, notes, and snippets.

@ejain
Created December 10, 2014 00:52
Show Gist options
  • Save ejain/69796781f773ed64e430 to your computer and use it in GitHub Desktop.
Save ejain/69796781f773ed64e430 to your computer and use it in GitHub Desktop.
A JMH microbenchmark to determine if a JVM is optimizing divisions by two.
package benchmark;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
@State(Scope.Thread)
public class ArithmeticBenchmark {
@Benchmark
public long testDivide() {
long value = Long.MAX_VALUE;
while (value > 0) {
value /= 2;
}
return value;
}
@Benchmark
public long testShift() {
long value = Long.MAX_VALUE;
while (value > 0) {
value = value >>> 1;
}
return value;
}
public static void main(String... args) throws Exception {
Options opts = new OptionsBuilder()
.include(ArithmeticBenchmark.class.getSimpleName())
.mode(Mode.Throughput)
.warmupIterations(10)
.measurementIterations(10)
.jvmArgs("-server")
.forks(1)
.build();
new Runner(opts).run();
}
}
Benchmark Mode Samples Score Error Units
b.ArithmeticBenchmark.testDivide thrpt 10 3695399.946 ± 87327.372 ops/s
b.ArithmeticBenchmark.testShift thrpt 10 8091063.504 ± 114824.341 ops/s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment