1. 程式人生 > 其它 >基準測試JMH的demo

基準測試JMH的demo

整合到idea需要這些

    <dependencies>
        <dependency>
            <groupId>org.openjdk.jmh</groupId>
            <artifactId>jmh-core</artifactId>
            <version>1.23</version>
        </dependency>

        <dependency>
            <groupId>org.openjdk.jmh</groupId>
            <artifactId>jmh-generator-annprocess</artifactId>
            <version>1.23</version>
        </dependency>
    </dependencies>

  idea需要安裝外掛:JMH java Microbenchmark Harness

勾選上這個。

package com.player3;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

 
public class NumsSum{

    static List<Integer> nums = new ArrayList<>();
    static {
        Random r = new Random();
        for (int i = 0; i < 10000; i++) nums.add(1000000 + r.nextInt(1000000));
    }

    public static void foreach() {
        for (Integer num : nums) {
        //    System.out.println(num);
        }
    }

}

  測試程式碼:直接執行

package com.player3;

import org.openjdk.jmh.annotations.*;

public class PSTest {
    @Benchmark
    @Warmup(iterations = 1,time = 2)
    @Threads(2)
    @Fork(2)
    @BenchmarkMode(Mode.Throughput)
    @Measurement(iterations = 2,time = 2)
    public void testForEach() {
        NumsSum.foreach();
    }
}

  會生成壓測報告。根據報告進行程式碼調整。

本文來自部落格園,作者:三號小玩家,轉載請註明原文連結:https://www.cnblogs.com/q1359720840/p/15811103.html