Use jmh for Micro Benchmarking

  jmh

maven

        <dependency>
            <groupId>org.openjdk.jmh</groupId>
            <artifactId>jmh-core</artifactId>
            <version>1.17.5</version>
        </dependency>
        <dependency>
            <groupId>org.openjdk.jmh</groupId>
            <artifactId>jmh-generator-annprocess</artifactId>
            <version>1.17.5</version>
            <scope>provided</scope>
        </dependency>

Use

@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 5, time = 3, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 20, time = 3, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Benchmark)
public class DemoJmhTest {

    private String pid;

    @Setup
    public void init() {
       // prepare 
    }
    
    @TearDown
    public void destory() {
       // destory 
    }

    @Benchmark
    public void benchPrecondition(){
        try{
            Preconditions.checkNotNull(pid);
        }catch (Exception e){

        }
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(".*" +DemoJmhTest.class.getSimpleName()+ ".*")
                .forks(1)
                .build();
        new Runner(opt).run();
    }
}

BenchmarkMode type

Mode.Throughput

How many times can this method be called in a limited iteration
 

Mode.AverageTime

The average execution time of the method
 

Mode.SampleTime

Sampling and calculating the execution time of the method
 

Mode.SingleShotTime

Method’s Single Call Time/Total Call Time of a Batch
 

Attention

Read the test input from @State object and return the calculation result, which is convenient for JMH to eliminate redundant codes.
If you are testing the performance of a method, avoid looping through the method (repeatedly executing the original code in the method), thus reducing the number of method calls and causing inaccurate results. You should place looping calls outside the method.

doc