- Mastering High Performance with Kotlin
- Igor Kucherenko
- 155字
- 2021-06-25 20:55:26
Using black holes
You can use an instance of Blackhole explicitly, but it's really useful if you're going to consume several values with the black hole. In another case, this approach just affects readability and it would be better to just return the value. The next example demonstrates correct and incorrect cases:
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MyBenchmark {
double x1 = Math.PI;
double x2 = Math.PI * 2;
@Benchmark
public double baseline() {
return Math.log(x1);
}
@Benchmark
public double measureWrong() {
Math.log(x1);
return Math.log(x2);
}
@Benchmark
public double measureRight_1() {
return Math.log(x1) + Math.log(x2);
}
@Benchmark
public void measureRight_2(Blackhole bh) {
bh.consume(Math.log(x1));
bh.consume(Math.log(x2));
}
}
The output shows how the JVM eliminates the first line of the measureWrong() method:
Benchmark Mode Cnt Score Error Units
MyBenchmark.baseline avgt 5 24.385 ± 1.559 ns/op
MyBenchmark.measureRight_1 avgt 5 43.861 ± 4.813 ns/op
MyBenchmark.measureRight_2 avgt 5 47.041 ± 4.800 ns/op
MyBenchmark.measureWrong avgt 5 24.447 ± 2.333 ns/op
推薦閱讀
- 深入理解Bootstrap
- DevOps with Kubernetes
- Mastering Selenium WebDriver
- 64位匯編語言的編程藝術
- Internet of Things with Intel Galileo
- R的極客理想:工具篇
- MATLAB for Machine Learning
- Linux:Embedded Development
- C語言程序設計
- FFmpeg開發實戰:從零基礎到短視頻上線
- Python一行流:像專家一樣寫代碼
- Java Web動態網站開發(第2版·微課版)
- Mastering JavaScript Promises
- Mastering Unity 2017 Game Development with C#(Second Edition)
- Modern R Programming Cookbook