Execute below command to create a maven jmh archetype
mvn archetype:generate \ -DinteractiveMode=false \ -DarchetypeGroupId=org.openjdk.jmh \ -DarchetypeArtifactId=jmh-java-benchmark-archetype \ -DgroupId=com.demo \ -DartifactId=JMHDemo \ -Dversion=1.0
You can import this project into eclipse. File > Import > Existing Maven Project
Lets create a JMH benchmark to compare looping of array list. Example below
package com.demo; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; 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.infra.Blackhole; 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; /* http://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/ */ @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @State(Scope.Benchmark) @Fork(value = 2, jvmArgs = {"-Xms2G", "-Xmx2G"}) //@Warmup(iterations = 3) //@Measurement(iterations = 8) public class BenchmarkLoop { @Param({"10000000"}) private int N; private List<String> DATA_FOR_TESTING; public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() .include(BenchmarkLoop.class.getSimpleName()) .forks(1) .build(); new Runner(opt).run(); } @Setup public void setup() { DATA_FOR_TESTING = createData(); } @Benchmark public void loopFor(Blackhole bh) { for (int i = 0; i < DATA_FOR_TESTING.size(); i++) { String s = DATA_FOR_TESTING.get(i); //take out n consume, fair with foreach bh.consume(s); } } @Benchmark public void loopWhile(Blackhole bh) { int i = 0; while (i < DATA_FOR_TESTING.size()) { String s = DATA_FOR_TESTING.get(i); bh.consume(s); i++; } } @Benchmark public void loopForEach(Blackhole bh) { for (String s : DATA_FOR_TESTING) { bh.consume(s); } } @Benchmark public void loopIterator(Blackhole bh) { Iterator<String> iterator = DATA_FOR_TESTING.iterator(); while (iterator.hasNext()) { String s = iterator.next(); bh.consume(s); } } private List<String> createData() { List<String> data = new ArrayList<>(); for (int i = 0; i < N; i++) { data.add("Number : " + i); } return data; } }
- Eclipse Maven Clean
- Eclipse Maven Install
- Run as a Java Application