第一步:添加依赖:

<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>

第二步:创建类:
/**
 * @desc:
 * @author: 毛会懂
 * @create: 2021-11-16 13:32:00
 **/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 5,time = 1,timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5,time = 1,timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Benchmark)
public class JMHFirstBenchmark {

    private BarrageService barrageService;

    @Setup(Level.Trial)
    public void setUp(){
        // 启动应用程序
        ConfigurableApplicationContext run = SpringApplication.run(xxxxApplicationBootstrap.class);
        // 从spring中拿Bean
        barrageService = run.getBean(BarrageService.class);
    }

    @Benchmark
    public void barrage(Blackhole bh1) throws InterruptedException {
        BarrageDTO barrage = new BarrageDTO();
        barrage.setActivityId(5368);
        ApiResult activityBarrages = barrageService.getActivityBarrages(barrage);
        bh1.consume(activityBarrages); // 防止jit陷阱
    }

    public static void main(String[] args) throws RunnerException {
        Options build = new OptionsBuilder().include(JMHFirstBenchmark.class.getSimpleName())
                .build();
        new Runner(build).run();
    }
}

问题:jmh执行完, 应用还在启动中,会报错,但不影响jmh的使用。
posted on 2021-11-17 10:37  毛会懂  阅读(364)  评论(1编辑  收藏  举报