[programming tips-dan-trik]

How to Create Benchmark Units in Golang

The testing package, 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.

package main

import "math"

type Tabung struct {
	Jarijari, Tinggi float64
}

func (t Tabung) Volume() float64 {
	return math.Phi * math.Pow(t.Jarijari, 2) * t.Tinggi
}

func (t Tabung) Luas() float64 {
	return 2 * math.Phi * t.Jarijari * (t.Jarijari + t.Tinggi)
}

func (t Tabung) KelilingAlas() float64 {
	return 2 * math.Phi * t.Jarijari
}

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.

func BenchmarkHitungLuas(b *testing.B) {
	tabung := Tabung{Jarijari: 7, Tinggi: 10}
	for i := 0; i < b.N; i++ {
		tabung.Luas()
	}
}

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.

➜  tabung git:(main) ✗ go test -v -bench=.              
=== RUN   TestTabung_Volume
=== RUN   TestTabung_Volume/testing_hitung_volume
--- PASS: TestTabung_Volume (0.00s)
    --- PASS: TestTabung_Volume/testing_hitung_volume (0.00s)
=== RUN   TestTabung_Luas
=== RUN   TestTabung_Luas/testing_hitung_luas_permukaan
--- PASS: TestTabung_Luas (0.00s)
    --- PASS: TestTabung_Luas/testing_hitung_luas_permukaan (0.00s)
=== RUN   TestTabung_KelilingAlas
=== RUN   TestTabung_KelilingAlas/testing_hitung_keliling_alas
--- PASS: TestTabung_KelilingAlas (0.00s)
    --- PASS: TestTabung_KelilingAlas/testing_hitung_keliling_alas (0.00s)
goos: darwin
goarch: arm64
pkg: github.com/santekno/tabung
BenchmarkHitungLuas
BenchmarkHitungLuas-8           1000000000               0.3317 ns/op
PASS
ok      github.com/santekno/tabung      2.557s

How 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.

comments powered by Disqus