JMH是新的microbenchmark(微基準測試)框架(2013年首次發佈)。與其餘衆多框架相比它的特點優點在於,它是由Oracle實現JIT的相同人員開發的。特別是我想提一下Aleksey Shipilev和他優秀的博客文章。JMH可能與最新的Oracle JRE同步,其結果可信度很高。java
使用JMH僅需知足2個必要條件(其餘全部都是建議選項):windows
<dependencies> <!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-core --> <dependency> <groupId>org.openjdk.jmh</groupId> <artifactId>jmh-core</artifactId> <version>1.15</version> </dependency> <!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-generator-annprocess --> <dependency> <groupId>org.openjdk.jmh</groupId> <artifactId>jmh-generator-annprocess</artifactId> <version>1.15</version> </dependency> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>
在eclipse market中搜索m2e 找到這個:框架
並安裝eclipse
在eclipse: windows-> preference-> Maven->Annotation Processing中 勾選第一個選項 如圖:maven
官方有個jmh的示例 helloworld性能
http://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/測試
我再附一個例子,測試兩個方法的性能:ui
package jmh; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Scope; 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; @State(value = Scope.Benchmark) public class Test { private int a[] = new int[5]; @Benchmark @BenchmarkMode(Mode.SampleTime) public void badTry() { int result = 0; int i = 0; try { while (true) { result += this.a[i++]; } } catch (ArrayIndexOutOfBoundsException e) { // do nothing } } @Benchmark @BenchmarkMode(Mode.SampleTime) public void goodTry() { int result = 0; for (int i = 0; i < a.length; i++) { result += this.a[i]; } } public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() .include(Test.class.getSimpleName()) .forks(0) .build(); new Runner(opt).run(); } }
須要注意的是,運行jmh main 中就是這樣寫的,而後在方法上加上註解就能夠跑了this