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
在有時限的迭代里頭沛膳,該方法能被調用多少次
Mode.AverageTime
方法平均執(zhí)行時間
Mode.SampleTime
對方法執(zhí)行時間進行采樣計算
Mode.SingleShotTime
方法的單次調用時間/一次批處理的總調用時間
注意點
從@State對象讀取測試輸入并返回計算的結果惕蹄,方便JMH對冗余代碼進行消除僻弹;
如果是測試方法的性能系任,則避免通過在方法內(nèi)循環(huán)(重復執(zhí)行方法內(nèi)原來代碼)马绝,這樣造成方法方法調用次數(shù)的減少曙痘,結果不準確腰耙,應該把循環(huán)調用放在方法外頭。