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