JMH入门
什么是JMH
JMH(Java Microbenchmark Harness)是一个在OpenJDK项目中发布的,专门用来进行性能测试的框架,其精度可以达到毫秒级。通过JMH可以对多个方法的性能进行定量分析。比如,执行一个函数需要多少时间,或者当对一个算法有不同实现时,哪一个的性能最好。
使用JMH
使用Maven导入JMH的jar包
<dependencies>
<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-core -->
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.21</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.21</version>
<scope>provided</scope>
</dependency>
</dependencies>
JMH程序
public class JMH_Test {
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public static void helloJMH(){
//冒泡排序
int[] array = {94, 12, 34, 76, 26, 9, 0, 37, 55, 76, 37, 5, 68, 83, 90, 37, 12, 65, 76, 49};
int temp;//用于交换数据的暂存单元
for (int i = array.length - 1; i >= 0; i--) {//将数组的最大索引视为“水面”
//数组的最小索引视为“水底”,“气泡”从“水底”向“水面”上浮
//因为i每减少一个,就有一个“气泡”上浮到最终位置,所以只需要对1到i之间的元素进行交换排序即可。
for (int j = 1; j <= i; j++) {
if (array[j - 1] > array[j]) {//如果上浮过程中发现比当前元素小的,就交换
temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
//System.out.println(Arrays.toString(array));
}
public static void main(String[] args) {
Options opt1 = new OptionsBuilder().include(JMH_Test.class.getSimpleName())
.forks(1).build();
try {
new Runner(opt1).run();
} catch (RunnerException e) {
e.printStackTrace();
}
}
}
被度量的代码用@Benchmark 标注。在main()函数中,进行配置。使用Builder模式配置测试,将配置参数存入Options对象,并使用Options对象构造Runner启动测试。
执行结果
Benchmark Mode Cnt Score Error Units
JMH_Test.helloJMH avgt 5 0.146 ± 0.067 us/op
平均花费时间为0.146us,误差为0.067us。