JMH, pour Java Microbenchmark Harness, est un framework de microbenchmarking (assez récent, fin 2013).
Son principal avantage, par rapport aux autres frameworks, est qu'il est développé par les mêmes personnes - dans Oracle - qui mettent en œuvre le JIT et en particulier, Aleksey Shipilev (http://shipilev.net/).
JMH est intégré aux outils livrés avec OpenJDK.
Prérequis:
pour hg cf. http://mercurial.selenic.com/
pour mvn cf. http://maven.apache.org/
1. Installation
Livré avec les tools java
ou
Récupération de la dernière version :
$hg clone http://hg.openjdk.java.net/code-tools/jmh/jmh $cd [pathToJmh]/jmh/ $mvn clean install -DskipTests
2. Utilisation
Création projet de test "test", "JMH-driven" avec maven
$ mvn archetype:generate -DinteractiveMode=false -DarchetypeGroupId=org.openjdk.jmh -DarchetypeArtifactId=jmh-java-benchmark-archetype -DgroupId=org.sample -DartifactId=test -Dversion=1.0
Ceci produit le hello word du test en annotation:
package org.sample;
import org.openjdk.jmh.annotations.Benchmark;
public class MyBenchmark { @Benchmark public void testMethod() { // This is a demo/sample template for building your JMH benchmarks. Edit as needed. // Put your benchmark code here. } }
Jmh est simple d'utilisation. Il supporte plusieurs modes d'utilisation:
- En ligne de commande :
$ mvn clean install $ java -jar target/benchmarks.jar MyTestClass -wi 5 -i 5 -f 1 #-wi 5 5 warmup/measurement #-i 5 5 iterations #-f 1 single fork
- Par l'api java annotation et/ou chaînage de méthodes :
@State(Scope.Thread) @OutputTimeUnit(TimeUnit.MICROSECONDS) @Fork(1) public class MyTestClass {
int i = 0;
@Benchmark @Warmup(iterations = 5, time = 100, timeUnit = TimeUnit.MILLISECONDS) @Measurement(iterations = 5, time = 100, timeUnit = TimeUnit.MILLISECONDS) public int myMethod() { return i++; }
public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() .include(MyTestClass.class.getSimpleName()) .warmupIterations(5) .measurementIterations(5) .forks(1) .build();
new Runner(opt).run(); } }
De nombreux exemples, permettant d'illustrer les différentes options de test, sont fournis par JMH:
http://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/
Parmi ceux-ci on peut citer :
- Les modes de mesures Throughput, AverageTime, SampleTime, SingleShotTime (cf.JMHSample_02_BenchmarkModes.java)
- La charge machine tunable Blackhole.consumeCPU(XX) (cf. JMHSample_21_ConsumeCPU.java)
- La constitution de lots
- Des options d'instruction pour le compilateur
- Etc.
Sources:
http://openjdk.java.net/projects/code-tools/jmh/
http://shipilev.net/talks/jvmls-July2014-benchmarking.pdf
http://shipilev.net/talks/devoxx-Nov2013-benchmarking.pdf
https://www.youtube.com/watch?v=W2gCocCI8QU
http://java-performance.info/introduction-jmh-profilers/
http://java.dzone.com/articles/microbenchmarking-jmh-measure
Auteur : Mathieu Penot