How to Create Benchmark Units in Golang
The testing package in Golang Programming, apart from containing tools for testing, also contains tools for benchmarking. The way to create a benchmark itself is quite easy, namely by creating a function whose name begins with Benchmark and whose parameters are of type *testing.B.
Create a program in the main.go file
Create a program like the one below, where in this program there is a Tube Struct which will consist of several methods, including the following.
First, prepare a Tube struct. We will later use the object variables resulting from this struct as testing material.
1package main
2
3import "math"
4
5type Tabung struct {
6 Jarijari, Tinggi float64
7}
8
9func (t Tabung) Volume() float64 {
10 return math.Phi * math.Pow(t.Jarijari, 2) * t.Tinggi
11}
12
13func (t Tabung) Luas() float64 {
14 return 2 * math.Phi * t.Jarijari * (t.Jarijari + t.Tinggi)
15}
16
17func (t Tabung) KelilingAlas() float64 {
18 return 2 * math.Phi * t.Jarijari
19}Then, we will test the performance of calculating the area of the tube. Prepare a function with the name BenchmarkCalculateArea() with the contents of the following code.
1func BenchmarkHitungLuas(b *testing.B) {
2 tabung := Tabung{Jarijari: 7, Tinggi: 10}
3 for i := 0; i < b.N; i++ {
4 tabung.Luas()
5 }
6}Run the test using the argument -bench=., this argument is used to indicate that apart from testing there is also a benchmark that needs to be tested.
1➜ tabung git:(main) ✗ go test -v -bench=.
2=== RUN TestTabung_Volume
3=== RUN TestTabung_Volume/testing_hitung_volume
4--- PASS: TestTabung_Volume (0.00s)
5 --- PASS: TestTabung_Volume/testing_hitung_volume (0.00s)
6=== RUN TestTabung_Luas
7=== RUN TestTabung_Luas/testing_hitung_luas_permukaan
8--- PASS: TestTabung_Luas (0.00s)
9 --- PASS: TestTabung_Luas/testing_hitung_luas_permukaan (0.00s)
10=== RUN TestTabung_KelilingAlas
11=== RUN TestTabung_KelilingAlas/testing_hitung_keliling_alas
12--- PASS: TestTabung_KelilingAlas (0.00s)
13 --- PASS: TestTabung_KelilingAlas/testing_hitung_keliling_alas (0.00s)
14goos: darwin
15goarch: arm64
16pkg: github.com/santekno/tabung
17BenchmarkHitungLuas
18BenchmarkHitungLuas-8 1000000000 0.3317 ns/op
19PASS
20ok github.com/santekno/tabung 2.557sHow to read Benchmark results
The meaning of 1000000000 0.3317 ns/op is, the function above was tested 1 billion times, the result is that it takes an average of 0.3317 nano seconds to run one function.