为什么 JMH 说返回 1 比返回 0 快
2022-09-01 23:09:19
有人可以解释为什么JMH说返回1比返回0更快吗?
下面是基准代码。
import org.openjdk.jmh.annotations.*;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Fork(value = 3, jvmArgsAppend = {"-server", "-disablesystemassertions"})
public class ZeroVsOneBenchmark {
@Benchmark
@Warmup(iterations = 3, time = 2, timeUnit = TimeUnit.SECONDS)
public int zero() {
return 0;
}
@Benchmark
@Warmup(iterations = 3, time = 2, timeUnit = TimeUnit.SECONDS)
public int one() {
return 1;
}
}
结果如下:
# Run complete. Total time: 00:03:05
Benchmark Mode Samples Score Score error Units
c.m.ZeroVsOneBenchmark.one thrpt 60 1680674.502 24113.014 ops/ms
c.m.ZeroVsOneBenchmark.zero thrpt 60 735975.568 14779.380 ops/ms
对于 1、2 和 0 具有相同的行为
# Run complete. Total time: 01:01:56
Benchmark Mode Samples Score Score error Units
c.m.ZeroVsOneBenchmark.one thrpt 90 1762956.470 7554.807 ops/ms
c.m.ZeroVsOneBenchmark.two thrpt 90 1764642.299 9277.673 ops/ms
c.m.ZeroVsOneBenchmark.zero thrpt 90 773010.467 5031.920 ops/ms