Home > Article > Backend Development > Performance benchmarking in Golang function testing
Performance benchmarks in Go measure function efficiency by writing benchmark code in functions that begin with Benchmark. The testing.B type provides ResetTimer(), StopTimer(), and N properties to control benchmark behavior. For example, a benchmark of the function that calculates Fibonacci numbers shows that executing Fib(30) takes about 2,767,425 nanoseconds. Optimize benchmark code to avoid overhead and run multiple times for accurate results.
Performance benchmarking in Go function testing
Performance benchmarking is an important tool for measuring function efficiency. In Go, the testing
package provides functionality for benchmarking function execution times.
Writing a performance benchmark test
Writing a performance benchmark test requires creating a function starting with Benchmark
, followed by the name of the function to be tested :
func BenchmarkFib(b *testing.B) { // 基准测试代码 }
Using the testing.B
testing.B
type provides the following methods to control the benchmark:
ResetTimer()
: Reset the timer. StopTimer()
: Stop the timer and record the time. N
: Number of times the benchmark test was performed. Practical Case
Let’s benchmark a function that calculates Fibonacci numbers:
func Fib(n int) int { if n <= 1 { return n } return Fib(n-1) + Fib(n-2) } func BenchmarkFib(b *testing.B) { for i := 0; i < b.N; i++ { Fib(30) } }
Run in the terminal Test:
go test -bench=.
The output will look like this:
BenchmarkFib 2767425 ns/op
This means that a benchmark of executing the Fib
function with 30 as argument takes approximately 2,767,425 nanoseconds (2767 milliseconds).
Tip
-benchmem
flag to measure memory allocation for the benchmark. The above is the detailed content of Performance benchmarking in Golang function testing. For more information, please follow other related articles on the PHP Chinese website!