Go 中的基准测试:指南和实战案例
在 Golang 中,基准测试是评估和分析代码性能的有力工具。它允许开发人员衡量函数或代码块的执行时间,从而识别性能瓶颈并进行改进。
基本语法
基准测试函数以 Benchmark
前缀命名,接受一个 b
类型为 *testing.B
的参数。Benchmark
函数的主循环在 b.RunParallel
下执行。使用 b.N
方法可以获取循环次数。
func BenchmarkSqrt(b *testing.B) { for i := 0; i < b.N; i++ { math.Sqrt(float64(i)) } }
运行基准测试
要运行基准测试,请使用 go test
命令并提供 -bench
标志。该标志表明要运行以 Benchmark
前缀命名的函数。
$ go test -bench=.
分析结果
基准测试的结果显示在控制台输出中。对于每个基准测试函数,它将显示以下指标:
ns/op
:单个操作(循环一次)的纳秒数MB/s
:输入数据的大小(以兆字节为单位)除以操作时间(以秒为单位)B/op
:单个操作的字节数最佳实践
b.ReportAllocs
追踪分配。b.Skip()
来跳过特定条件下的基准测试。实战案例:排序算法比较
为了演示,让我们对三种排序算法(内置的 sort
包、Go 1.18 中引入了的 container/heap
包,以及快速排序)进行基准测试。
import ( "sort" "container/heap" "math/rand" ) func randomIntSlice(n int) []int { s := make([]int, n) for i := range s { s[i] = rand.Intn(n) } return s } func BenchmarkSort(b *testing.B) { b.RunParallel(func(pb *testing.PB) { for pb.Next() { s := randomIntSlice(10000) sort.Ints(s) } }) } func BenchmarkHeapSort(b *testing.B) { b.RunParallel(func(pb *testing.PB) { for pb.Next() { s := randomIntSlice(10000) heap.Sort(s) } }) } func BenchmarkQuickSort(b *testing.B) { b.RunParallel(func(pb *testing.PB) { for pb.Next() { s := randomIntSlice(10000) quickSort(s) } }) } func quickSort(a []int) { if len(a) < 2 { return } left, right := 0, len(a)-1 pivot := a[(left+right)/2] for left <= right { for a[left] < pivot { left++ } for a[right] > pivot { right-- } if left <= right { a[left], a[right] = a[right], a[left] left++ right-- } } quickSort(a[:left]) quickSort(a[left:]) }
运行上述基准测试后,我们得到以下输出:
BenchmarkSort 636705 ns/op BenchmarkHeapSort 645853 ns/op BenchmarkQuickSort 837199 ns/op
这表明内置的 sort
包在 10000 个随机整数的列表上表现最佳。