看看这个简单的基准测试:
@State(Scope.Benchmark)
@Fork(value = 1)
@Warmup(iterations = 3, time = 300, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@BenchmarkMode(Mode.Throughput)
public class SimpleBenchmark {
int[] array;
@Setup
public void setup() {
this.array = new int[100_000];
}
@Benchmark
public void dec_all() {
for(int i = 0; i < this.array.length; i++){
this.array[i]--;
}
}
@Benchmark
public void dec_half() {
for(int i = 0; i < this.array.length; i+=2){
this.array[i]--;
}
}
}
选项 #1 - 终端。如果您使用的是 maven,您的 pom.xml
中将需要类似的内容
[...]
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>${uberjar.name}</finalName>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
<filters>
<filter>
<!-- Shading signed JARs will fail without this. http://stackoverflow.com/questions/999489/invalid-signature-file-when-attempting-to-run-a-jar -->
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
然后在终端/控制台中运行它:
mvn clean package
java -jar target/benchmarks.jar
选项 #2 - IDE。在 IDE 中从 main 运行它:
import org.openjdk.jmh.Main;
[...]
public static void main(String... args) throws Exception {
Main.main(args); // WARN: for better results run it from terminal!
}
结果你会看到:
Benchmark Mode Cnt Score Error Units
SimpleBenchmark.dec_all thrpt 10 37278,685 ± 757,013 ops/s
SimpleBenchmark.dec_half thrpt 10 28749,803 ± 811,464 ops/s
由于@BenchmarkMode(Mode.Throughput),您将获得 [ops/s](操作数/秒)。尝试其他模式,例如AverageTime
你也可以试试这个模板:https://github.com/jawb-software/template-jmh-benchmark/tree/simple