<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(); } }
在有时限的迭代里头,该方法能被调用多少次
java
方法平均执行时间
maven
对方法执行时间进行采样计算
ide
方法的单次调用时间/一次批处理的总调用时间
性能
从@State对象读取测试输入并返回计算的结果,方便JMH对冗余代码进行消除;
若是是测试方法的性能,则避免经过在方法内循环(重复执行方法内原来代码),这样形成方法方法调用次数的减小,结果不许确,应该把循环调用放在方法外头。测试
jmhui