Skip to content

Instantly share code, notes, and snippets.

@netudima
Created March 21, 2020 07:38
Show Gist options
  • Save netudima/e1e8206bf58ff0ab6e2d637a4362bfc2 to your computer and use it in GitHub Desktop.
Save netudima/e1e8206bf58ff0ab6e2d637a4362bfc2 to your computer and use it in GitHub Desktop.
benchmark different int log2 options
package com.github.netudima.cassandra;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class NettyLog2Benchmark {
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(NettyLog2Benchmark.class.getSimpleName())
.forks(3)
.build();
new Runner(opt).run();
// check equivalence of the implementations in range [0; Integer.MAX_VALUE]
// for(int i = 0; i < Integer.MAX_VALUE; i++) {
// int log1 = log2LeadingZeroes(i);
// int log2 = log2Cycle(i);
// int log3 = log2Bits(i);
// if (log1 != log2 || log2 != log3) {
// System.out.println("i: " + i + ", log1: " + log1 + ", log2: " + log2 + ", log3: " + log3);
// }
// }
}
@State(Scope.Thread)
public static class MyState {
public int value = 1234567;
}
@Benchmark
public int leadingZeroes(MyState myState) {
return log2LeadingZeroes(myState.value);
}
@Benchmark
public int cycle(MyState myState) {
return log2Cycle(myState.value);
}
@Benchmark
public int bits(MyState myState) {
return log2Bits(myState.value);
}
private static int log2LeadingZeroes(int val) {
if (val == 0) {
return 0;
}
return 31 - Integer.numberOfLeadingZeros(val);
}
private static int log2Cycle(int val) {
int res = 0;
while (val > 1) {
val >>= 1;
res++;
}
return res;
}
private static int log2Bits(int val) {
int log = 0;
if( ( val & 0xffff0000 ) != 0 ) { val >>>= 16; log = 16; }
if( val >= 256 ) { val >>>= 8; log += 8; }
if( val >= 16 ) { val >>>= 4; log += 4; }
if( val >= 4 ) { val >>>= 2; log += 2; }
return log + ( val >>> 1 );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment