参考资料:
http://www.importnew.com/12548.html
http://blog.csdn.net/hfmbook/article/details/70209150
依赖库:
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.9.3</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.9.3</version>
<scope>provided</scope>
</dependency>
Main方法:
import com.nxg.JmhDemo;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
public class MyPro {
public static void main(String [] args) throws Exception{
Options opt = new OptionsBuilder()
.include(JmhDemo.class.getSimpleName())
.forks(1)
.warmupIterations(5) //预热次数
.measurementIterations(5) //真正执行次数
.build();
new Runner(opt).run();
}
}
测试类:
package com.nxg;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import java.util.concurrent.TimeUnit;
public class JmhDemo {
@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
public void stringLoop(){
String str = new String();
for(int i = 0; i<100; i++){
str += "str\t";
str += "str\t";
str += "str\t";
str += "str\t";
str += "str\t";
}
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
public void builderLoop(){
StringBuilder builder = new StringBuilder();
for(int i = 0; i<100; i++){
builder.append("str\t");
builder.append("str\t");
builder.append("str\t");
builder.append("str\t");
builder.append("str\t");
}
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
public void bufferLoop(){
StringBuffer buffer = new StringBuffer();
for(int i = 0; i < 100; i++){
buffer.append("str\t");
buffer.append("str\t");
buffer.append("str\t");
buffer.append("str\t");
buffer.append("str\t");
}
}
}
总结:基本上我们的代码都可以这么测试一下,尤其是需要对一些库进行选择的时候,非常好用。