前言
jmh的简单使用说明
jmh version:1.18
jdk version: 1.8
使用maven添加jmh-core和jmh-generator-annprocess
case-1
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@Threads(2)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@BenchmarkMode(Mode.Throughput)
@State(Scope.Benchmark)
public class JMHCase1 {
ObjectMapper om = new ObjectMapper();
@State(Scope.Benchmark)
public static class UserInfo {
int age;
String name;
int sex;
double salary;
String location;
int isMarried;
Date birthday;
String mobile;
String idCardNo;
String job;
@Setup(Level.Trial)
public void init() {
age = 18;
name = "Roronoa-Zoro";
sex = 1;
salary = 20000.1;
location = "One Piece";
isMarried = 0;
birthday = new Date();
mobile = "1380000000";
idCardNo = "11012011912345";
job = "fighter";
}
}
@Benchmark
public String fastjsonTest(UserInfo userInfo) {
String result = JSON.toJSONString(userInfo);
// JSON.parseObject(result, UserInfo.class);
return result;
}
@Benchmark
public String jacksonTest(UserInfo userInfo) throws IOException {
String result = om.writeValueAsString(userInfo);
// om.readValue(result, UserInfo.class);
return result;
}
@Test
public void starter() throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHCase1.class.getSimpleName())
.build();
new Runner(opt).run();
}
}
参数说明
@Warmup, 进行预热,正式基准测试前进行
@Measurement, 正式基准测试,包括执行几次,每次执行的时间
@Fork, 表示每个基准测试执行几轮
@Threads, 表示启用几个线程
@OutputTimeUnit, 表示输出结果时的时间单位
@BenchmarkMode, 表示基准测试采集的数据,有吞吐量,平均执行时间,抽样统计方法的执行时间,其他见源码参数注释
@State, 表示是每个线程独有还是在这一次基准测试过程中共享
结果说明
Benchmark Mode Cnt Score Error Units
JMHCase1.fastjsonTest thrpt 5 5396.680 ± 646.910 ops/ms
JMHCase1.jacksonTest thrpt 5 4641.159 ± 755.968 ops/ms
上面的error的±表示误差幅度, score和units则表示每毫秒有多少操作数
case-2
@Warmup(iterations = 2, time = 50, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 2, time = 50, timeUnit = TimeUnit.MILLISECONDS)
@Fork(1)
@Threads(1)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@BenchmarkMode(Mode.Throughput)
@State(Scope.Benchmark)
public class JMHCase2 {
@Param({"hello", "world", "jmh"})
String argument;
@Benchmark
public void showParamUsage() {
System.out.println("argument value=" + argument);
}
@Test
public void starter() throws RunnerException {
Options opt = new OptionsBuilder()
.include(JMHCase2.class.getSimpleName())
.build();
new Runner(opt).run();
}
}
参数说明
主要添加了@param, 就是可以给参数赋值,而且上例中有3个值,则基准测试会针对每个参数值执行一次