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

使用

@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類型

Mode.Throughput

在有時限的迭代裏頭,該方法能被調用多少次
 java

Mode.AverageTime

方法平均執行時間
 maven

Mode.SampleTime

對方法執行時間進行採樣計算
 ide

Mode.SingleShotTime 

方法的單次調用時間/一次批處理的總調用時間
 性能

注意點

從@State對象讀取測試輸入並返回計算的結果,方便JMH對冗餘代碼進行消除;
若是是測試方法的性能,則避免經過在方法內循環(重複執行方法內原來代碼),這樣形成方法方法調用次數的減小,結果不許確,應該把循環調用放在方法外頭。測試

doc

相關文章
相關標籤/搜索