The Go language comes with a powerful testing framework, including the Benchmark function, which is used to measure and evaluate the performance of a piece of code.
We can create benchmarks by writing specially formatted functions in Go's test files. The naming of test files follows 原函数名称_test.go
the format of .
The name of the benchmark function must start with "Benchmark", followed by the name of the test you want to name, and the only parameter of the function is a pointer to it *testing.B
. For example:
func BenchmarkMyFunction(b *testing.B) {
for i := 0; i < b.N; i++ {
// 执行你想要测试性能的代码
}
}
In the benchmark function, put the code you want to test in a b.N
loop against . b.N
is a very large number, and the Go testing framework will automatically adjust its value so that the benchmark function runs long enough to get more accurate results.
go test -bench=.
Benchmarks are performed by running them from the command line . -bench
The flag is followed by a regular expression that matches the name of the benchmark function you want to run, .
meaning match all files.
go test -bench=.
Benchmark results will show the average time of each operation, you can use this result to evaluate the performance of your code, or compare the performance differences of different versions or different implementations.
example:
func BenchmarkTest(b *testing.B) {
str := ""
for i := 0; i < b.N; i++ {
str += "a"
}
}
output:
goos: darwin
goarch: arm64
pkg: awesomeProject3
BenchmarkTest
BenchmarkTest-12 1000000 28001 ns/op
PASS
goos: darwin
: Benchmark running OSgoarch: arm64
: The processor architecture the benchmark runs onpkg: awesomeProject3
: The Go package that the benchmark runs onBenchmarkTest
: Benchmark function nameBenchmarkTest-12
: Benchmarking and its degree of parallelism. Here it is running with a parallelism of 12.1000000
: number of benchmark function runs28001 ns/op
: The time required to run the benchmark function each time, in nanoseconds. Here it is 28001 nanoseconds, which is 0.028001 milliseconds.PASS
: Indicates that the benchmark passed