Learning GO [DAY-3]

Hello all, logging my Day-3 learnings here.

Today we’ll see about benchmarking programs in Go Benchmarking again is an in-built feature of Go. It comes under the testing package.

Syntax

Benchmarking can be used by creating a special function of a specific form. This exposes the utilities in testing.B type.

The function itself is in the form,

func BenchmarkFunctionName(b *testing.B)

Some info

These Benchmark functions can be evoked using the go test command with the -bench flag. Benchmark functions run sequentially.

command example

go test -bench=.

Using Benchmark function

Let us see a simple example of benchmarking a for loop in Go For this we need two files again,

  1. loop_test.go
  2. loop.go , and as usual go.mod file too.
// loop_test.go

package iteration
import "testing"

func TestRepeat(t *testing.T){
        got := Repeat("a")
        want := "aaaaa"

        if got != want {
                t.Errorf("Expected %q, but got %q", want, got)
        }
}
// benchmarking function
func BenchmarkRepeat(b *testing.B){
        for i := 0; i < b.N; i++ {
                Repeat("a")
        }
}

The above snippet contains the benchmark function called BenchmarkRepeat having b as a argument which points to the B type in the testing package.

Inside the function block, it contains a for loop running for b.N times, this is provided by the testing package for our use.

// loop.go

package iteration

const repeatCount = 5

func Repeat(letter string) string {
        var resString string
        // for loop
        for i := 0; i < repeatCount; i++ {
                resString += letter
        }
        return resString
}

This is a simple letter repaeating program written in Go. This loops in the range of 5 and adds the letter to the existing string. It returns the result string.

After saving these two files and type the go test -bench=. command in the WD.

This runs the benchmark function and yields the below as output,

goos: windows
goarch: amd64
pkg: loop.go
cpu: Intel(R) Core(TM) iX-XXXXXX CPU @ X.XXGHz
BenchmarkRepeat-4        5288964               225.6 ns/op
PASS
ok      loop.go 2.807s

The output contains the OS, SYS-Architecture, package we are testing/benchmarking( loop.go ), CPU information and the execution speed which is 225.6 nanoseconds.

So that’s all for today! I learned about Arrays and Slicing today, which I’ll be discussing tomorrow. I’ll also make sure to discuss about range looping and some other stuffs too.

Until then signing off,

~/CR08