Skip to content

Instantly share code, notes, and snippets.

@mbien
Created Dec 3, 2021
Embed
What would you like to do?
Simple RandomGenerator JMH benchmark
package dev.mbien.jmh;
import java.util.concurrent.TimeUnit;
import java.util.random.RandomGenerator;
import java.util.random.RandomGeneratorFactory;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.results.format.ResultFormatType;
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;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Benchmark)
public class RandomJMH {
@Param({})
public String name;
private RandomGenerator rng;
@Setup(Level.Iteration)
public void setup() {
rng = RandomGeneratorFactory.of(name).create(42);
}
@Benchmark
public void rngInt(Blackhole bh) throws InterruptedException {
rng.nextInt();
}
@Benchmark
public void rngLong(Blackhole bh) throws InterruptedException {
rng.nextLong();
}
public static void main(String[] args) throws RunnerException {
String[] names = RandomGeneratorFactory.all()
.map(t -> t.name()).sorted().toArray(String[]::new);
Options opt = new OptionsBuilder()
.include(RandomJMH.class.getSimpleName())
.resultFormat(ResultFormatType.JSON)
.result("results/"+RandomJMH.class.getSimpleName()+".json")
.param("name", names)
.build();
new Runner(opt).run();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment