JMH基准测试
JMH 简介
JMH,即 Java Microbenchmark Harness,这是专 ⻔ ⽤于进 ⾏代码的微基准测试的 ⼀套 ⼯具 API,JMH 由 OpenJDK/Oracle ⾥ ⾯那群开发了 Java 编译器的人员所开发。
使用场景
- 已经找出了热点函数,⽽需要对热点函数进 ⾏进 ⼀步的优化时,就可以使 ⽤ JMH 对优化的效 果进 ⾏定量的分析。
- 想定量地知道某个函数需要执 ⾏多 ⻓时间,以及执 ⾏时间和输 ⼊ n 的相关性
- ⼀个函数有两种不同实现(例如 JSON 序列化/反序列化有 Jackson 和 Gson 实现),不知道哪种 实现性能更好
快速上手
引入依赖
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.21</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.21</version>
<scope>provided</scope>
</dependency>
编写基准测试类(战 SpringBoot 整合 JMH)
import org.openjdk.jmh.annotations.*;
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 org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
@State(Scope.Thread)
public class JMHSpringbootTest {
private ConfigurableApplicationContext context;
private CouponService couponService;
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(JMHSpringbootTest.class.getName() + ".*") //指定基准测试的方法
.warmupIterations(2) //预热
.measurementIterations(2) //正式计量
.forks(1).build();
new Runner(options).run();
}
/**
* setup初始化容器的时候只执行一次
*/
@Setup(Level.Trial)
public void init(){
String arg = "";
context = SpringApplication.run(CouponAppApplication.class,arg);
couponService = context.getBean(CouponService.class);
}
/**
* benchmark执行多次,此注解代表触发我们所要进行基准测试的方法
*/
@Benchmark
public void test(){
System.out.println(couponService.getCouponList());
}
}
测试结果
# Run complete. Total time: 00:01:27
REMEMBER: The numbers below are just data. To gain reusable insights, you need to follow up on
why the numbers are the way they are. Use profilers (see -prof, -lprof), design factorial
experiments, perform baseline and negative tests that provide experimental control, make sure
the benchmarking environment is safe on JVM/OS/HW level, ask for reviews from the domain experts.
Do not assume the numbers tell you what you want them to tell.
Benchmark Mode Cnt Score Error Units
JMHSpringbootTest.test thrpt 2 680.070 ops/s