JMH 的使用及示例

1.JMH的介绍

 JMH是新的microbenchmark(微基准测试)框架(2013年首次发布)。与其他众多框架相比它的特色优势在于,它是由Oracle实现JIT的相同人员开发的。特别是我想提一下Aleksey Shipilev和他优秀的博客文章。JMH可能与最新的Oracle JRE同步,其结果可信度很高。

  
2. 使用JMH

使用JMH仅需满足2个必要条件(其他所有都是建议选项):

  •     设置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 找到这个:

104819_CjVj_2561483.png

并安装

2.3 在IDE的preference中勾选自动启动 apt

在eclipse:  windows-> preference-> Maven->Annotation Processing中 勾选第一个选项 如图:

105037_ALJ6_2561483.png

 

3 demo

官方有个jmh的示例 helloworld

http://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/

我再附一个例子,测试两个方法的性能:

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 中就是这样写的,然后在方法上加上注解就可以跑了

 

 

 

转载于:https://my.oschina.net/u/2561483/blog/755660

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值