DevilKing's blog

冷灯看剑,剑上几分功名?炉香无需计苍生,纵一穿烟逝,万丈云埋,孤阳还照古陵

0%

JMH intro

原文链接

JMH (Java Microbenchmark Harness)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.mkyong.benchmark;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
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.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
@Fork(value = 2, jvmArgs = {"-Xms2G", "-Xmx2G"})
//@Warmup(iterations = 3)
//@Measurement(iterations = 8)
public class BenchmarkLoop {

@Param({"10000000"})
private int N;

private List<String> DATA_FOR_TESTING;

public static void main(String[] args) throws RunnerException {

Options opt = new OptionsBuilder()
.include(BenchmarkLoop.class.getSimpleName())
.forks(1)
.build();

new Runner(opt).run();
}

@Setup
public void setup() {
DATA_FOR_TESTING = createData();
}

@Benchmark
public void loopFor(Blackhole bh) {
for (int i = 0; i < DATA_FOR_TESTING.size(); i++) {
String s = DATA_FOR_TESTING.get(i); //take out n consume, fair with foreach
bh.consume(s);
}
}

@Benchmark
public void loopWhile(Blackhole bh) {
int i = 0;
while (i < DATA_FOR_TESTING.size()) {
String s = DATA_FOR_TESTING.get(i);
bh.consume(s);
i++;
}
}

@Benchmark
public void loopForEach(Blackhole bh) {
for (String s : DATA_FOR_TESTING) {
bh.consume(s);
}
}

@Benchmark
public void loopIterator(Blackhole bh) {
Iterator<String> iterator = DATA_FOR_TESTING.iterator();
while (iterator.hasNext()) {
String s = iterator.next();
bh.consume(s);
}
}

private List<String> createData() {
List<String> data = new ArrayList<>();
for (int i = 0; i < N; i++) {
data.add("Number : " + i);
}
return data;
}

}

主要是针对单个函数部分进行benchmark的测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>benchmarks</finalName>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>