package 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 java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

// Benchmark                   Mode  Cnt  Score   Error  Units
// JMHExample01.arrayListAdd   avgt   10  0.085 ± 0.364  us/op
// JMHExample01.linkedListAdd  avgt   10  0.007 ± 0.001  us/op
@BenchmarkMode({Mode.AverageTime})
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Thread)
@Measurement(iterations = 5)// 度量5个批次
@Warmup(iterations = 3)// 预热3个批次
public class JMHExample01 {
    private final static String DATA = "DUMMY DATA";

    private List<String> arrayList;
    private List<String> linkedList;

    public static void main(String[] args) throws RunnerException {
        final Options opt = new OptionsBuilder().include(JMHExample01.class.getSimpleName())
                .forks(1)
                .measurementIterations(10)// 度量执行的批次为10，在这个5个批次中对基准方法执行与调用将会纳入统计
                .warmupIterations(10)// 在真正的度量之前，首先会对代码进行10个批次的预热，是代码运行达到JVM已经优化的效果
                .build();
        new Runner(opt).run();
    }

    @Setup(Level.Iteration)
    public void setUp() {
        this.arrayList = new ArrayList<>();
        this.linkedList = new ArrayList<>();
    }

    @Benchmark
    public List<String> arrayListAdd() {
        this.arrayList.add(DATA);
        return this.arrayList;
    }

    @Benchmark
    public List<String> linkedListAdd() {
        this.linkedList.add(DATA);
        return this.linkedList;
    }
}
