我想用JMH做一个非常简单的基准测试:方法的三轮非并行运行并打印每个计时。 我对结果有些困惑。比分是多少?如何打印实际时间?
这是样本结果打印
Result "runs":
0,779 ±(99.9%) 0,326 ops/s [Average]
(min, avg, max) = (0,101, 0,779, 1,738), stdev = 0,375
CI (99.9%): [0,453, 1,104] (assumes normal distribution)
# Run complete. Total time: 00:02:08
Benchmark Mode Cnt Score Error Units
SimpleJaxInsert.runs thrpt 20 0,779 ± 0,326 ops/s
我还真的需要这段代码吗?在这里,您可以看到一些没有Runner
类用法http://tutorials.jenkov.com/java-performance/jmh.html#state-scope的工作台,但我无法使其工作。在哪里可以找到JMH使用的最小示例(可能直到2018年)?
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(SimpleJaxInsert.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true).shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
答案 0 :(得分:0)
看看这个简单的基准:
@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