- 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
推薦閱讀
- AngularJS入門與進階
- 構建移動網站與APP:HTML 5移動開發入門與實戰(跨平臺移動開發叢書)
- 深入淺出Prometheus:原理、應用、源碼與拓展詳解
- C語言程序設計基礎與實驗指導
- AIRAndroid應用開發實戰
- Visual Basic程序設計實踐教程
- 程序設計基礎教程:C語言
- 數據結構案例教程(C/C++版)
- Mastering Linux Security and Hardening
- Java Web應用開發項目教程
- Django 5企業級Web應用開發實戰(視頻教學版)
- Akka入門與實踐
- Learning Kotlin by building Android Applications
- Neo4j 3.x入門經典
- Mastering Leap Motion