基準測試
最後更新
本頁說明如何用
BenchmarkXxx 函式量測程式的執行速度與記憶體配置,並用 go test -bench 執行。什麼是基準測試
基準測試(benchmark)回答的問題是「這段程式跑一次要多久、配置多少記憶體」。它和單元測試寫在同一個
_test.go 檔,但目的不同:單元測試檢查「對不對」,基準測試量測「快不快」。常見用途:
- 比較兩種寫法哪個快(例如字串用
+=串接還是用strings.Builder) - 改程式前後各量一次,確認最佳化真的有效
- 找出配置太多記憶體的熱點,再配合 pprof 深入分析
| 元素 | 規則 |
|---|---|
| 函式名稱 | BenchmarkXxx,簽名為 func(b *testing.B) |
| 執行 | go test -bench=<regexp>;不加 -bench 時基準測試不會執行 |
| 量測區 | for b.Loop() { ... } 迴圈內的程式碼 |
注意:基準測試的數字(ns/op、迭代次數)會因 CPU、作業系統、背景負載而不同。本頁輸出取自 Apple M5,你的機器跑出來的數字一定不一樣,請看相對差異而非絕對值。
撰寫與執行基準測試
BenchmarkXxx 與 b.Loop
Go 1.24 起,基準測試的標準寫法是
for b.Loop() { ... }。測試框架會反覆呼叫迴圈本體,直到量測時間足夠(預設 1 秒),再算出每次操作的平均耗時。簽名:
- func (b *B) Loop() bool
b.Loop 有兩個好處:- 迴圈之前的準備工作(setup)不會算進量測時間,第一次呼叫
b.Loop時計時器會自動歸零 - 迴圈內的函式呼叫結果會被保留,編譯器不會因為「結果沒被使用」就把整段程式最佳化掉
被測程式
join.go:- package join
- import "strings"
- func Concat(words []string) string {
- s := ""
- for _, w := range words {
- s += w
- }
- return s
- }
- func Builder(words []string) string {
- var b strings.Builder
- for _, w := range words {
- b.WriteString(w)
- }
- return b.String()
- }
測試檔
join_test.go:- package join
- import "testing"
- func BenchmarkConcat(b *testing.B) {
- words := make([]string, 100)
- for i := range words {
- words[i] = "go"
- }
- for b.Loop() {
- Concat(words)
- }
- }
執行(
go.mod 的 module 為 example.com/join):- go test -bench=.
輸出:
- goos: darwin
- goarch: arm64
- pkg: example.com/join
- cpu: Apple M5
- BenchmarkConcat-10 673951 1810 ns/op
- PASS
- ok example.com/join 1.460s
讀法:
| 欄位 | 意義 |
|---|---|
BenchmarkConcat-10 | 名稱;-10 是執行時的 GOMAXPROCS |
673951 | 總共執行了幾次迴圈本體 |
1810 ns/op | 平均每次操作耗時 1810 奈秒 |
-bench 的值是正規表示式,. 代表全部。這些數字因機器而異。傳統的 b.N 迴圈
Go 1.24 以前的寫法是自己寫一個跑
b.N 次的迴圈。框架會用不同的 b.N(1、100、10000...)多次呼叫整個基準函式,直到時間夠長。因此迴圈外的準備工作也會跑很多次,需要用 b.ResetTimer() 把準備時間扣掉。你在既有專案或舊文章中還會看到這種寫法,認得即可;新程式用
b.Loop。兩種寫法不要混用在同一個函式裡。測試檔
join_test.go(被測程式同上):- package join
- import "testing"
- func makeWords() []string {
- words := make([]string, 100)
- for i := range words {
- words[i] = "go"
- }
- return words
- }
- func BenchmarkConcatN(b *testing.B) {
- words := makeWords()
- b.ResetTimer()
- for range b.N {
- Concat(words)
- }
- }
- func BenchmarkConcatLoop(b *testing.B) {
- words := makeWords()
- for b.Loop() {
- Concat(words)
- }
- }
執行:
- go test -bench=.
輸出:
- goos: darwin
- goarch: arm64
- pkg: example.com/join
- cpu: Apple M5
- BenchmarkConcatN-10 617286 2050 ns/op
- BenchmarkConcatLoop-10 624459 2068 ns/op
- PASS
- ok example.com/join 3.777s
兩種寫法量到的結果相近(數字因機器而異)。差別在於
b.Loop 版本不必手動 ResetTimer,也不怕編譯器把沒用到的結果最佳化掉。-benchmem 量測記憶體配置
加上
-benchmem 旗標,輸出會多兩欄:每次操作配置的位元組數(B/op)與配置次數(allocs/op)。記憶體配置越多,GC 的負擔越重,往往也是速度慢的原因。測試檔
join_test.go(被測程式同上):- package join
- import "testing"
- func makeWords() []string {
- words := make([]string, 100)
- for i := range words {
- words[i] = "go"
- }
- return words
- }
- func BenchmarkConcat(b *testing.B) {
- words := makeWords()
- for b.Loop() {
- Concat(words)
- }
- }
- func BenchmarkBuilder(b *testing.B) {
- words := makeWords()
- for b.Loop() {
- Builder(words)
- }
- }
執行:
- go test -bench=. -benchmem
輸出:
- goos: darwin
- goarch: arm64
- pkg: example.com/join
- cpu: Apple M5
- BenchmarkConcat-10 651861 1834 ns/op 10736 B/op 99 allocs/op
- BenchmarkBuilder-10 4040949 293.0 ns/op 504 B/op 6 allocs/op
- PASS
- ok example.com/join 2.615s
+= 每串一次就配置一個新字串,100 個字詞配置了 99 次;strings.Builder 只在內部緩衝區不夠時才擴充,配置次數少很多,速度也快數倍。耗時數字因機器而異,但配置次數與位元組數在同一版 Go 下通常是固定的。如果想讓某個基準測試不加旗標也印出配置資訊,可以在函式內呼叫
b.ReportAllocs()。b.Run 子基準與 -benchtime
和單元測試的
t.Run 一樣,b.Run 可以建立子基準測試,常用來比較同一個函式在不同輸入大小下的表現。-benchtime 控制量測多久:預設 1s;寫成 2000x 代表固定跑 2000 次。測試檔
join_test.go(被測程式同上):- package join
- import (
- "fmt"
- "testing"
- )
- func BenchmarkBuilder(b *testing.B) {
- for _, n := range []int{10, 100, 1000} {
- words := make([]string, n)
- for i := range words {
- words[i] = "go"
- }
- b.Run(fmt.Sprintf("n=%d", n), func(b *testing.B) {
- for b.Loop() {
- Builder(words)
- }
- })
- }
- }
執行:
- go test -bench=Builder -benchmem -benchtime=2000x
輸出:
- goos: darwin
- goarch: arm64
- pkg: example.com/join
- cpu: Apple M5
- BenchmarkBuilder/n=10-10 2000 101.5 ns/op 56 B/op 3 allocs/op
- BenchmarkBuilder/n=100-10 2000 740.7 ns/op 504 B/op 6 allocs/op
- BenchmarkBuilder/n=1000-10 2000 5848 ns/op 5368 B/op 10 allocs/op
- PASS
- ok example.com/join 0.258s
迭代次數固定為 2000;耗時大致隨輸入量線性成長,數字因機器而異。次數少時結果的波動較大,正式比較時建議用預設的時間模式,並加
-count=5 多跑幾輪觀察是否穩定。注意:基準測試期間請關掉其他吃 CPU 的程式;筆電接電源、避免過熱降頻,否則前後兩次的數字可能差很多。
重點整理
- 基準測試寫成
func BenchmarkXxx(b *testing.B),用go test -bench=.執行 - Go 1.24 起用
for b.Loop() { ... },setup 自動不計時,結果也不會被編譯器最佳化掉 - 舊式
for range b.N需要b.ResetTimer();兩種寫法不要混用 -benchmem顯示B/op與allocs/op,配置越少通常越快b.Run建立子基準,-benchtime、-count控制量測長度與輪數- ns/op 數字因機器而異,只比較同一台機器上的相對差異