Java中的基准测试JMH简单使用
Contents
使用
命令行
请参考官方网站:
Maven
pom.xml
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.15</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.15</version>
</dependency>
使用示例:
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
/**
* Created by emacsist on 2017/6/12.
*/
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Thread)
public class BenchmarkTest {
@Benchmark
public void testJSON(){
add(1, 3);
}
public static int add(int a, int b){
return a + b;
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(BenchmarkTest.class.getSimpleName())
.forks(1)
.warmupIterations(5)
.measurementIterations(5)
.threads(10)
.build();
new Runner(opt).run();
}
}
说明
Mode:表示测试类型,它有 Throughput(吞吐量), AverageTime(平均时间), SampleTime(取样时间), SingleShotTime(测量单次操作),All(前面所有类型) OutputTimeUnit:输出的时间单位
warmupIterations:表示预热,消除JIT的影响 measurementIterations:表示测量的次数
输出例子
比如上面的代码的输出为
# Warmup Iteration 1: 2304.433 ops/us
# Warmup Iteration 2: 2817.992 ops/us
# Warmup Iteration 3: 3895.650 ops/us
# Warmup Iteration 4: 3912.852 ops/us
# Warmup Iteration 5: 4092.241 ops/us
Iteration 1: 4133.110 ops/us
Iteration 2: 4465.652 ops/us
Iteration 3: 4754.479 ops/us
Iteration 4: 5023.710 ops/us
Iteration 5: 4653.248 ops/us
Result "testJSON":
4606.040 ±(99.9%) 1280.132 ops/us [Average]
(min, avg, max) = (4133.110, 4606.040, 5023.710), stdev = 332.446
CI (99.9%): [3325.908, 5886.172] (assumes normal distribution)
# Run complete. Total time: 00:00:12
Benchmark Mode Cnt Score Error Units
BenchmarkTest.testJSON thrpt 5 4606.040 ± 1280.132 ops/us
Process finished with exit code 0