Measure, don’t guess!
JMH适用场景
JMH只适合细粒度的方法测试
原理
编译时会生成一些测试代码,一般都会继承你的类
maven依赖
org.openjdk.jmh
jmh-core
${jmh.version}
org.openjdk.jmh
jmh-generator-annprocess
${jmh.version}
provided
UTF-8
1.0
1.6
benchmarks
命令行方式:
生成测试项目
mvn archetype:generate \-DinteractiveMode=false\-DarchetypeGroupId=org.openjdk.jmh \-DarchetypeArtifactId=jmh-java-benchmark-archetype \-DgroupId=org.sample \-DartifactId=test \-Dversion=1.0
打包
$ cd test/$ mvn cleaninstall
执行,
java -jar target/benchmarks.jar
java -jar target/benchmarks.jar -h //查看帮助信息
插件方式
插件会影响执行效果,但最多不会超过 2.2%
A brief research shows that benchmark results are affected, but not that much. The whole research is described in Research results.
Long story short, the maximum means difference observed was 2.2%.
main函数
packageorg.openjdk.jmh.samples;importorg.openjdk.jmh.annotations.Benchmark;importorg.openjdk.jmh.runner.Runner;importorg.openjdk.jmh.runner.RunnerException;importorg.openjdk.jmh.runner.options.Options;importorg.openjdk.jmh.runner.options.OptionsBuilder;public classJMHSample_01_HelloWorld {/** This is our first benchmark method.
*
* JMH works as follows: users annotate the methods with @Benchmark, and
* then JMH produces the generated code to run this particular benchmark as
* reliably as possible. In general one might think about @Benchmark methods
* as the benchmark "payload", the things we want to measure. The
* surrounding infrastructure is provided by the harness itself.
*
* Read the Javadoc for @Benchmark annotation for complete semantics and
* restrictions. At this point we only note that the methods names are
* non-essential, and it only matters that the methods are marked with
* @Benchmark. You can have multiple benchmark methods within the same
* class.
*
* Note: if the benchmark method never finishes, then JMH run never finishes
* as well. If you throw an exception from the method body the JMH run ends
* abruptly for this benchmark and JMH will run the next benchmark down the
* list.
*
* Although this benchmark meas