JMH
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.18</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.18</version>
<scope>test</scope>
</dependency>
- http://tutorials.jenkov.com/java-performance/jmh.html#getting-started-with-jmh
- http://www.importnew.com/12548.html
State
@State(Scope.Benchmark)
声明类实例是线程共享的,且所有线程共享一个实例
@State(Scope.Thread)
声明类实例是非线程共享的,且所有线程都实例话一个对象
Step
耗时不会计算在总时间里
Setup 和Junit中的Before类似
Level 说明
Level.Trial 默认,全部Benchmark之前
Level.Iteration 一组调用之前
Level.Invocation 每个方法调用之前
TearDown 和Junit中的@After类似
Fork
设置进程数,以及jvm启动参数
Threads
设置线程数,注意和State配合使用
@State(Scope.Benchmark)
@Fork(value = 1,
jvmArgsAppend = {"-server", "-Xms4g", "-Xmx4g", "-Xmn1536m", "-XX:CMSInitiatingOccupancyFraction=82", "-Xss256k",
"-XX:+DisableExplicitGC", "-XX:+UseConcMarkSweepGC", "-XX:+CMSParallelRemarkEnabled",
"-XX:LargePageSizeInBytes=128m", "-XX:+UseFastAccessorMethods",
"-XX:+UseCMSInitiatingOccupancyOnly", "-XX:+CMSClassUnloadingEnabled"})
@Threads(value = 1)
@BenchmarkMode({Mode.Throughput, Mode.AverageTime})
// time = 5,timeUnit = TimeUnit.SECONDS 意思是每个迭代测量的时间限制在5s
@Measurement(iterations = 3, time = 100, timeUnit = TimeUnit.SECONDS)
@Warmup(iterations = 1, time = 100, timeUnit = TimeUnit.SECONDS)
@OutputTimeUnit(TimeUnit.SECONDS)
public class AopAliLogTest {
private HelloService helloService;
private CommonService commonService;
// 其实也可以放在static中。
// 不过指明 @Setup 不会计算在总时间里
@Setup(Level.Trial)
public void init() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("application.xml");
helloService = ctx.getBean(HelloService.class);
commonService = ctx.getBean(CommonService.class);
}
@Benchmark
public void testAliLogCreateOrder() {
String result = helloService.createOrder("arg1", "arg2");
Assert.isTrue("arg1 arg2".equals(result));
}
@Benchmark
public void testCommonCreateOrder() {
String result = commonService.createOrder("arg1", "arg2");
Assert.isTrue("arg1 arg2".equals(result));
}
// 可以选择安装idea的插件启动,也可以用main函数启动,还可以打包测试
public static void main(String[] args) throws Exception {
Options opt = new OptionsBuilder()
.include(AopAliLogTest.class.getSimpleName())
.build();
new Runner(opt).run();
}
}
网友评论