feat: JMHExample12

This commit is contained in:
Bunny 2025-01-19 15:47:36 +08:00
parent 78ff512f26
commit c8c2a0e8bc
1 changed files with 72 additions and 0 deletions

View File

@ -0,0 +1,72 @@
package cn.bunny.jmh;
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)
@Fork(0)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Thread)
public class JMHExample12 {
private final Inc inc1 = new Inc1();
private final Inc inc2 = new Inc2();
public static void main(String[] args) throws RunnerException {
final Options options = new OptionsBuilder()
.include(JMHExample12.class.getSimpleName())
.build();
new Runner(options).run();
}
private int measure(Inc inc) {
int result = 0;
for (int i = 0; i < 10; i++) {
result += inc.inc();
}
return result;
}
@Benchmark
public int measure_inc_1() {
return this.measure(inc1);
}
@Benchmark
public int measure_inc_2() {
return this.measure(inc2);
}
@Benchmark
public int measure_inc_3() {
return this.measure(inc1);
}
interface Inc {
int inc();
}
public static class Inc1 implements Inc {
private int i = 0;
@Override
public int inc() {
return ++i;
}
}
public static class Inc2 implements Inc {
private int i = 0;
@Override
public int inc() {
return ++i;
}
}
}