Skip to content

Instantly share code, notes, and snippets.

@little-arhat
Created August 4, 2020 21:33
Show Gist options
  • Save little-arhat/37fec0be8bcc4a992b91f508ce27ff11 to your computer and use it in GitHub Desktop.
Save little-arhat/37fec0be8bcc4a992b91f508ce27ff11 to your computer and use it in GitHub Desktop.
bench
package com.github.larhat;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
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 org.openjdk.jmh.runner.options.TimeValue;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public class Main {
private final static int FIRST_BOOK_ID = 3512512;
private final static int LAST_BOOK_ID = 3512512 * 4;
private final static int TOTAL_NUMBER = 141553;
private final static int TOTAL_EVENTS = 429392;
@State(Scope.Benchmark)
public static class BenchmarkState {
private Set<Long> theHashSet;
private BookIds theBookIds;
private long[] theSelected;
private int thePos = 0;
private long theCur;
@Setup(Level.Trial)
public void setup() {
int myPerExpiry = TOTAL_NUMBER / 32;
theHashSet = new HashSet<>(myPerExpiry);
Random myRandom = new Random();
for (int myI = 0; myI < myPerExpiry; myI++) {
theHashSet.add((long)FIRST_BOOK_ID + myRandom.nextInt(LAST_BOOK_ID));
}
theSelected = new long[TOTAL_EVENTS];
for (int myI = 0; myI < theSelected.length; myI++) {
theSelected[myI] = (long)FIRST_BOOK_ID + myRandom.nextInt(LAST_BOOK_ID);
}
theBookIds = BookIds.create(theHashSet, Long::longValue);
}
@Setup(Level.Invocation)
public void setupCounter() {
thePos = (thePos + 1) % theSelected.length;
theCur = theSelected[thePos];
}
}
@Benchmark
public boolean hashSet(BenchmarkState aBenchmarkState) {
return aBenchmarkState.theHashSet.contains(aBenchmarkState.theCur);
}
@Benchmark
public boolean bookIds(BenchmarkState aBenchmarkState) {
return aBenchmarkState.theBookIds.contains(aBenchmarkState.theCur);
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(Main.class.getSimpleName())
.mode(Mode.AverageTime)
.timeUnit(TimeUnit.NANOSECONDS)
.warmupIterations(10)
.measurementIterations(30)
.measurementTime(TimeValue.seconds(5))
.forks(1)
.build();
new Runner(opt).run();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment