feat: JMHExample10

This commit is contained in:
Bunny 2025-01-19 15:29:51 +08:00
parent 09792f158c
commit 922393d2d9
1 changed files with 56 additions and 0 deletions

View File

@ -0,0 +1,56 @@
package cn.bunny.jmh;
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.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@Fork(1)
@Warmup(iterations = 5)
@Measurement(iterations = 10)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Thread)
public class JMHExample10 {
double x1 = Math.PI;
double x2 = Math.PI * 2;
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(JMHExample10.class.getSimpleName())
.build();
new Runner(options).run();
}
@Benchmark
public double baseline() {
// 不是 Dead Code
return Math.pow(x1, x2);
}
@Benchmark
public double powButReturnOne() {
// Dead Code 会被擦除
Math.pow(x1, x2);
// Dead Code 不会擦除因为返回了
return Math.pow(x1, x2);
}
@Benchmark
public double powThenAdd() {
// 对两个结果都进行了计算所以都会生效
return Math.pow(x1, x2) + Math.pow(x1, x2);
}
@Benchmark
public void useBlackWhole(Blackhole blackhole) {
blackhole.consume(Math.pow(x1, 2));
blackhole.consume(Math.pow(x2, 2));
}
}