0%

JMH

文章字数:251,阅读全文大约需要1分钟

简介

JMHJDK9自带的JVM基准测试套件,用于定位代码性能,执行时间、吞吐量等

构建

  1. 通过maven依赖引入
1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.23</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.23</version>
</dependency>
  1. 直接生成maven工程(官方推荐)
1
2
3
4
5
6
7
mvn archetype:generate 
-DinteractiveMode=false
-DarchetypeGroupId=org.openjdk.jmh
-DarchetypeArtifactId=jmh-java-benchmark-archetype
-DgroupId=com.test.jmh
-DartifactId=jmh
-Dversion=1.0.0-SNAPSHOT

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 预热5次,每次1s
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
// 循环运行5次,总共5秒
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
// 1个线程运行基准测试
@Fork(1)
// 平均时间
@BenchmarkMode(Mode.AverageTime)
// 纳秒,和上面的组合就是每次操作的纳秒单位的平均时间
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class MyBenchmark {

@GenerateMicroBenchmark
public List<Integer> testMethod() {
int cardCount = 54;
List<Integer> cardList = new ArrayList<Integer>();
for (int i=0; i<cardCount; i++){
cardList.add(i);
}
// 洗牌算法
Random random = new Random();
for (int i=0; i<cardCount; i++) {
int rand = random.nextInt(cardCount);
Collections.swap(cardList, i, rand);
}
return cardList;
}
}

Mean + Units就是每次操作的毫秒数

1
2
Benchmark                        Mode   Samples         Mean   Mean error    Units
c.a.j.MyBenchmark.testMethod avgt 5 1056.677 30.809 ns/op

@BenchmarkMode(Mode.Throughput)@OutputTimeUnit(TimeUnit.MILLISECONDS)组合,就是每毫秒吞吐量

943.437 ops/ms

1
2
Benchmark                        Mode   Samples         Mean   Mean error    Units
c.a.j.MyBenchmark.testMethod thrpt 5 943.437 44.060 ops/ms