JMH 的使用及示例

1.JMH的介紹

 JMH是新的microbenchmark(微基準測試)框架(2013年首次發佈)。與其餘衆多框架相比它的特點優點在於,它是由Oracle實現JIT的相同人員開發的。特別是我想提一下Aleksey Shipilev和他優秀的博客文章。JMH可能與最新的Oracle JRE同步,其結果可信度很高。java

  
2. 使用JMH

使用JMH僅需知足2個必要條件(其餘全部都是建議選項):windows

  •     設置jmh-core的maven依賴
  •  使用註解測試方法

2.1 在pom.xml中添加以下內容:

<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>

2.2 安裝m2e-apt

在eclipse market中搜索m2e 找到這個:框架

並安裝eclipse

2.3 在IDE的preference中勾選自動啓動 apt

在eclipse:  windows-> preference-> Maven->Annotation Processing中 勾選第一個選項 如圖:maven

 

3 demo

官方有個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

相關文章
相關標籤/搜索