JMH

241 阅读1分钟

java microbenchmark harness

<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-core -->
<dependency>
    <groupId>org.openjdk.jmh</groupId>
    <artifactId>jmh-core</artifactId>
    <version>1.33</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-generator-annprocess -->
<dependency>
    <groupId>org.openjdk.jmh</groupId>
    <artifactId>jmh-generator-annprocess</artifactId>
    <version>1.33</version>
    <scope>test</scope>
</dependency>
package com.jmh;

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

public class PS {

    static List<Integer> nums  = new ArrayList<>();

    static{
        Random r = new Random();
        for (int i = 0;  i < 1000; i++){
            nums.add(1000000 + r.nextInt(1000000));
        }
    }

    static void foreach(){
        nums.forEach(v->isPrime(v));
    }

    static void parallel(){
        nums.parallelStream().forEach(PS::isPrime);
    }

    static boolean isPrime(int num){
        for (int i = 2; i<= num / 2; i++){
            if (num % i == 0){
                return false;
            }
        }
        return true;
    }
}
package com.jmh;

import org.openjdk.jmh.annotations.*;

public class PSTest {

    @Benchmark
    // 预热,由于jvm中对于特定代码会存在优化(本地化),预热对于测试结果很重要
    @Warmup(iterations = 1, time = 3)
    @Fork(5)
    @BenchmarkMode(Mode.Throughput)
    @Measurement(iterations = 1, time = 3)
    public void testForEach(){
        PS.foreach();
    }
}

note: Environment variables 勾上 include parent Environment variables