Overview of Benchmark Testing in Golang


In this article we are going to discuss an overview of Benchmark testing. Benchmark testing is a basic portion of program optimization to grade the execution and productivity of code. In Golang, benchmark testing is backed through the built-in testing bundle. Here we are going to use the Benchmark function along with examples to elaborate on the concept.

Syntax

time.duration()

This function is used to represent the time interval in go language. It allows the user to work with time durations.

time.sleep()

We use this function to stop the execution of a go language program for a specific duration.

Algorithm

  • Write benchmark functions with the prefix "Benchmark" and implement the logic you want to measure.

  • Run the benchmarks using the "go test" command with the "-bench" flag.

  • Analyze the benchmark results for metrics like execution time and memory allocations.

  • Optimize your code based on the results and repeat the benchmarking process.

  • Optionally, add assertions to verify performance expectations.

  • Document the benchmark results and any optimizations made.

Example

In this example, we have defined a function MyFunction that performs a simple calculation. The BenchmarkFunction is the benchmark entry point, which repeatedly calls MyFunction in a loop b.N times. To run the benchmark, we use the testing.Benchmark function, passing the BenchmarkFunction as the argument. The testing.Benchmark function automatically performs the necessary iterations and collects the benchmarking results.

package main

import (
   "fmt"
   "testing"
   "time"
)

func MyFunction(n int) int {
   result := 0
   for i := 0; i < n; i++ {
      result += i
   }
   return result
}

func BenchmarkFunction(b *testing.B) {
   for i := 0; i < b.N; i++ {
      _ = MyFunction(100)
   }
}

func main() {
   timeout := time.Duration(10) * time.Second

   b := testing.B{}
	
   go func() {
      b.StartTimer()
      BenchmarkFunction(&b)
      b.StopTimer()
   }()

   time.Sleep(timeout)

   fmt.Printf("Ran %d iterations in %v\n", b.N, timeout)
}

Output

Ran 0 iterations in 10s

Conclusion

Benchmark testing in Golang may be an effective instrument for assessing the execution of code and optimizing it for superior productivity. By composing benchmark capacities and running them utilizing the testing bundle, designers can decrease execution time, memory utilization, and other measurements to recognize execution issues. 

Updated on: 20-Jul-2023

146 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements