使用JMH进行微基准测试
目的及介绍
- 有时候我们想测试一个方法,一个函数,一个类的执行效率,最土的办法莫过于做时间差:
long timebegin = System.nanoTime();
for(int timei = 0; timei < 10; timei++){
do somethings;
}
long timeend = System.nanoTime();
System.out.println("cost time:" + (timeend - timebegin));
- 这个方法虽然方便,简易,但是粗糙,不准确,今天介绍JMH,一款Java微基准测试工具,能够准确的给出这个方法的实际效率。
搭建、设计思路
- 引入 JMH 的 jar包
<dependencies>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.19</version>
<scope>provided</scope>
</dependency>
</dependencies>
- 主要注解
@BenchmarkMode
@OutputTimeUnit
@Iteration
@WarmUp
@State
@Fork
@Meansurement
@Setup
@TearDown
@Benchmark
@Param
实际用例
- 说明:我想测试我写的十二个排序方法效率如何,于是我分别如下:
- 主方法
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class InnerSortRealizeTimeTest {
@Test
public void sortTimeTest() throws RunnerException {
Options options = new OptionsBuilder().
include("SortTest")//此处是模糊匹配
.warmupIterations(2)//预热2轮
.measurementIterations(2)//实际2轮
.forks(2)//预热2轮+实际2轮算一组,这是循环2组
.build();
new Runner(options).run();
}
}
- 分别在所有待测试的方法上加上
@Benchmark
@BenchmarkMode(Mode.Throughput)
- 测试结果
Benchmark Mode Cnt Score Error Units
normalSortTest.BucketSortTest.TestInnerSortRealize thrpt 4 5235.110 ± 2652.157 ops/s
normalSortTest.CountSortTest.TestInnerSortRealize thrpt 4 9764.645 ± 6352.699 ops/s
normalSortTest.MergeSortTest.TestInnerSortRealize thrpt 4 2833.303 ± 483.073 ops/s
normalSortTest.RadixSortTest.TestInnerSortRealize thrpt 4 3862.049 ± 3743.130 ops/s
normalSortTest.ShellSortTest.TestInnerSortRealize thrpt 4 4150.777 ± 237.711 ops/s
quickSortTest.QuickSortDuplexingTest.TestInnerSortRealize thrpt 4 15079.496 ± 7921.672 ops/s
quickSortTest.QuickSortOptTest.TestInnerSortRealize thrpt 4 19513.197 ± 12820.824 ops/s
quickSortTest.QuickSortSimplexTest.TestInnerSortRealize thrpt 4 4347.717 ± 1105.995 ops/s
simpleSortTest.BubbleSortTest.TestInnerSortRealize thrpt 4 1780.624 ± 82.313 ops/s
simpleSortTest.HeapSortTest.TestInnerSortRealize thrpt 4 6892.012 ± 2643.572 ops/s
simpleSortTest.InsertSortTest.TestInnerSortRealize thrpt 4 9119.023 ± 3375.271 ops/s
simpleSortTest.SelectSortTest.TestInnerSortRealize thrpt 4 3108.758 ± 284.871 ops/s
-
结论
- 插排改的排序最优,每秒19513.197 ± 12820.824次,但是± 12820.824也表示这个算法每次表现的不稳定。
- 冒泡排序性能表现最稳定,每秒1780.624 ± 82.313次。
-
JMH 陷阱
-
JMH 插件
-
JMH 可视化
-
请参看下列博客:
-
参考博客