使用JMH进行微基准测试

使用JMH进行微基准测试

目的及介绍

  • 有时候我们想测试一个方法,一个函数,一个类的执行效率,最土的办法莫过于做时间差:
long timebegin = System.nanoTime();
for(int timei = 0; timei < 10; timei++){
    
    
    do somethings;
}
long timeend = System.nanoTime();
System.out.println("cost time:" + (timeend - timebegin));
  • 这个方法虽然方便,简易,但是粗糙,不准确,今天介绍JMH,一款Java微基准测试工具,能够准确的给出这个方法的实际效率。

搭建、设计思路

  • 引入 JMH 的 jar包
<dependencies>
    <dependency>
        <groupId>org.openjdk.jmh</groupId>
        <artifactId>jmh-core</artifactId>
        <version>1.19</version>
    </dependency>
    <dependency>
        <groupId>org.openjdk.jmh</groupId>
        <artifactId>jmh-generator-annprocess</artifactId>
        <version>1.19</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
  • 主要注解
@BenchmarkMode
@OutputTimeUnit
@Iteration
@WarmUp
@State
@Fork
@Meansurement
@Setup
@TearDown
@Benchmark
@Param

实际用例

@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class InnerSortRealizeTimeTest {
    
    
    @Test
    public void sortTimeTest() throws RunnerException {
    
    

        Options options = new OptionsBuilder().
                include("SortTest")//此处是模糊匹配
                .warmupIterations(2)//预热2轮
                .measurementIterations(2)//实际2轮
                .forks(2)//预热2轮+实际2轮算一组,这是循环2组
                .build();
        new Runner(options).run();
    }
}
  • 分别在所有待测试的方法上加上
@Benchmark
@BenchmarkMode(Mode.Throughput)
  • 测试结果
Benchmark                                                                                                                          Mode  Cnt      Score       Error  Units
normalSortTest.BucketSortTest.TestInnerSortRealize         thrpt    4   5235.110 ±  2652.157  ops/s
normalSortTest.CountSortTest.TestInnerSortRealize          thrpt    4   9764.645 ±  6352.699  ops/s
normalSortTest.MergeSortTest.TestInnerSortRealize          thrpt    4   2833.303 ±   483.073  ops/s
normalSortTest.RadixSortTest.TestInnerSortRealize          thrpt    4   3862.049 ±  3743.130  ops/s
normalSortTest.ShellSortTest.TestInnerSortRealize          thrpt    4   4150.777 ±   237.711  ops/s
quickSortTest.QuickSortDuplexingTest.TestInnerSortRealize  thrpt    4  15079.496 ±  7921.672  ops/s
quickSortTest.QuickSortOptTest.TestInnerSortRealize        thrpt    4  19513.197 ± 12820.824  ops/s
quickSortTest.QuickSortSimplexTest.TestInnerSortRealize    thrpt    4   4347.717 ±  1105.995  ops/s
simpleSortTest.BubbleSortTest.TestInnerSortRealize         thrpt    4   1780.624 ±    82.313  ops/s
simpleSortTest.HeapSortTest.TestInnerSortRealize           thrpt    4   6892.012 ±  2643.572  ops/s
simpleSortTest.InsertSortTest.TestInnerSortRealize         thrpt    4   9119.023 ±  3375.271  ops/s
simpleSortTest.SelectSortTest.TestInnerSortRealize         thrpt    4   3108.758 ±   284.871  ops/s

猜你喜欢

转载自blog.csdn.net/ljfirst/article/details/106543981