JMH Java基准测试
JMH是什么
JMH(Java Microbenchmark Harness)是Java基准测试工具
JMH使用方式
官方参考案例:https://github.com/openjdk/jmh/tree/master/jmh-samples/src/main/java/org/openjdk/jmh/samples
引入jmh依赖
<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>
实现代码
package com.test;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.results.format.ResultFormatType;
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;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 3)
@Measurement(iterations = 5)
@Threads(4)
@Fork(1)
@State(value = Scope.Benchmark)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class AddTest {
@Param(value = {"100", "1000", "10000"})
private int length;
private static int val1 = 0;
private static int val2 = 0;
private static int val3 = 0;
private Object o2 = new Object();
private Object o3 = new Object();
@Benchmark
public void method1(Blackhole blackhole) {
for (int i = 0; i < length; i++) {
m1();
}
blackhole.consume(val1);
}
public synchronized void m1() {
val1++;
}
public synchronized void m2() {
synchronized (o2) {
val2++;
}
}
public void m3() {
synchronized (o3) {
val3++;
}
}
@Benchmark
public void method2(Blackhole blackhole) {
for (int i = 0; i < length; i++) {
m2();
}
blackhole.consume(val2);
}
@Benchmark
public void method3(Blackhole blackhole) {
for (int i = 0; i < length; i++) {
m3();
}
blackhole.consume(val3);
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(AddTest.class.getSimpleName())
.result("result.json")
.resultFormat(ResultFormatType.JSON).build();
new Runner(opt).run();
}
}
以上代码,会将method1、method2、method3分别将 Param中的length 100、1000、10000执行一次,预热执行3次、正式执行5次,统计时间。也就是method1、method2、method3分别会执行24次
注释解释
@BenchmarkMode(Mode.AverageTime)
基准测试的模式,可选择吞吐量、平均响应时间等
Throughput("thrpt", "Throughput, ops/time"),
AverageTime("avgt", "Average time, time/op"),
SampleTime("sample", "Sampling time"),
SingleShotTime("ss", "Single shot invocation time"),
All("all", "All benchmark modes");
@Warmup(iterations = 3)
预热轮数
@Measurement(iterations = 5)
执行轮数
@Threads(4)
线程数
@Fork(1)
进程数
@State(value = Scope.Benchmark)
值共享的范围
Benchmark
Group
Thread
@OutputTimeUnit(TimeUnit.NANOSECONDS)
时间单位
@Param(value = {“100”, “1000”, “10000”})
参数,会将每个参数都执行一遍
@Benchmark
需要测试的方法
|