Java基准测试JMH

描述

本文描述JMH的用法。

示例

引入maven依赖


    org.openjdk.jmh
    jmh-core
    1.22


    org.openjdk.jmh
    jmh-generator-annprocess
    1.22
    provided

下面代码测试了正常方法调用和反射调用平均耗时。

@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class ReflectBenchMark {

    @Benchmark
    public Object reflect() {
        Baby baby = new Baby();

        Class aClass = baby.getClass();

        try {
            Method sayHello = aClass.getMethod("sayHello", null);

            Object invoke = sayHello.invoke(baby, null);

            return invoke;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Benchmark
    public String methodNormal() {
        Baby baby = new Baby();
        return baby.sayHello();
    }


    public static void main(String[] args) throws RunnerException {

        Options options = new OptionsBuilder()
                .include(ReflectBenchMark.class.getSimpleName())
                .forks(1)
                .build();

        new Runner(options).run();

    }

}

输出

...
Benchmark                      Mode  Cnt  Score    Error  Units
ReflectBenchMark.methodNormal  avgt    5  0.003 ±  0.001  us/op
ReflectBenchMark.reflect       avgt    5  0.176 ±  0.005  us/op
  • @BenchmarkMode
    测试类型:
    • Throughput:吞吐量,每个时间单位调用次数
    • AverageTime:平均时间,每次调用时间
    • SampleTime:
    • SingleShotTime:只运行一次,测试冷启动
    • all
  • @Warmup
    预热,iterations测试次数,time每次进行的时长,timeUnit时长单位
  • @Measurement
    实际执行,参数和Warmup一致

引用

http://blog.dyngr.com/blog/2016/10/29/introduction-of-jmh/
https://www.xncoding.com/2018/01/07/java/jmh.html
http://tutorials.jenkov.com/java-performance/jmh.html
https://lexburner.github.io/java-jmh/
https://caorong.github.io/2017/08/22/jmh-usage/
http://openjdk.java.net/projects/code-tools/jmh/

你可能感兴趣的:(Java基准测试JMH)