<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.20</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.20</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>run-benchmarks</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<classpathScope>test</classpathScope>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath />
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
2 测试代码:
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; @BenchmarkMode(Mode.AverageTime) //使用模式 :是对吞吐量 平均响应时间等 @Warmup(iterations = 3) //配置预热次数, 这里我们设置为3次 ,让Jvm该加载的都加载 //本例是一次运行5秒,总共运行3次 // 在性能对比时候,采用默认1秒即可, @Measurement(iterations = 3, time = 5, timeUnit = TimeUnit.SECONDS) @Threads(1) // 配置同时起多少个线程执行 ,也可以设置到方法上 @Fork(1) //代表启动多个单独的进程分别测试每个方法,我们这里指定为每个方法启动一个进程 @OutputTimeUnit(TimeUnit.NANOSECONDS) //OutputTimeUnit 统计结果的时间单位,这个例子的单位为 秒 public class JMHTestDemo { @Benchmark public void testStringAdd() { StringBuffer sb = new StringBuffer(); for (int i = 0; i < 1000; i++) { sb.append(i); } // System.out.println( sb.toString()); } @Benchmark public void testStringBuilderAdd() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1000; i++) { sb.append(i); } // System.out.println( sb.toString()); } public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() .include(JMHTestDemo.class.getSimpleName()) .build(); new Runner(opt).run(); } }
三、问题:
原文:https://www.cnblogs.com/lean-blog/p/13719524.html