基準測試

最後更新


本頁說明如何用 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 秒),再算出每次操作的平均耗時。
簽名:
  1. func (b *B) Loop() bool

b.Loop 有兩個好處:
  • 迴圈之前的準備工作(setup)不會算進量測時間,第一次呼叫 b.Loop 時計時器會自動歸零
  • 迴圈內的函式呼叫結果會被保留,編譯器不會因為「結果沒被使用」就把整段程式最佳化掉

被測程式 join.go:
  1. package join
  2. import "strings"
  3. func Concat(words []string) string {
  4. s := ""
  5. for _, w := range words {
  6. s += w
  7. }
  8. return s
  9. }
  10. func Builder(words []string) string {
  11. var b strings.Builder
  12. for _, w := range words {
  13. b.WriteString(w)
  14. }
  15. return b.String()
  16. }

測試檔 join_test.go:
  1. package join
  2. import "testing"
  3. func BenchmarkConcat(b *testing.B) {
  4. words := make([]string, 100)
  5. for i := range words {
  6. words[i] = "go"
  7. }
  8. for b.Loop() {
  9. Concat(words)
  10. }
  11. }

執行(go.mod 的 module 為 example.com/join):
  1. go test -bench=.

輸出:
  1. goos: darwin
  2. goarch: arm64
  3. pkg: example.com/join
  4. cpu: Apple M5
  5. BenchmarkConcat-10 673951 1810 ns/op
  6. PASS
  7. 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(被測程式同上):
  1. package join
  2. import "testing"
  3. func makeWords() []string {
  4. words := make([]string, 100)
  5. for i := range words {
  6. words[i] = "go"
  7. }
  8. return words
  9. }
  10. func BenchmarkConcatN(b *testing.B) {
  11. words := makeWords()
  12. b.ResetTimer()
  13. for range b.N {
  14. Concat(words)
  15. }
  16. }
  17. func BenchmarkConcatLoop(b *testing.B) {
  18. words := makeWords()
  19. for b.Loop() {
  20. Concat(words)
  21. }
  22. }

執行:
  1. go test -bench=.

輸出:
  1. goos: darwin
  2. goarch: arm64
  3. pkg: example.com/join
  4. cpu: Apple M5
  5. BenchmarkConcatN-10 617286 2050 ns/op
  6. BenchmarkConcatLoop-10 624459 2068 ns/op
  7. PASS
  8. ok example.com/join 3.777s

兩種寫法量到的結果相近(數字因機器而異)。差別在於 b.Loop 版本不必手動 ResetTimer,也不怕編譯器把沒用到的結果最佳化掉。

-benchmem 量測記憶體配置


加上 -benchmem 旗標,輸出會多兩欄:每次操作配置的位元組數(B/op)與配置次數(allocs/op)。記憶體配置越多,GC 的負擔越重,往往也是速度慢的原因。
測試檔 join_test.go(被測程式同上):
  1. package join
  2. import "testing"
  3. func makeWords() []string {
  4. words := make([]string, 100)
  5. for i := range words {
  6. words[i] = "go"
  7. }
  8. return words
  9. }
  10. func BenchmarkConcat(b *testing.B) {
  11. words := makeWords()
  12. for b.Loop() {
  13. Concat(words)
  14. }
  15. }
  16. func BenchmarkBuilder(b *testing.B) {
  17. words := makeWords()
  18. for b.Loop() {
  19. Builder(words)
  20. }
  21. }

執行:
  1. go test -bench=. -benchmem

輸出:
  1. goos: darwin
  2. goarch: arm64
  3. pkg: example.com/join
  4. cpu: Apple M5
  5. BenchmarkConcat-10 651861 1834 ns/op 10736 B/op 99 allocs/op
  6. BenchmarkBuilder-10 4040949 293.0 ns/op 504 B/op 6 allocs/op
  7. PASS
  8. 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(被測程式同上):
  1. package join
  2. import (
  3. "fmt"
  4. "testing"
  5. )
  6. func BenchmarkBuilder(b *testing.B) {
  7. for _, n := range []int{10, 100, 1000} {
  8. words := make([]string, n)
  9. for i := range words {
  10. words[i] = "go"
  11. }
  12. b.Run(fmt.Sprintf("n=%d", n), func(b *testing.B) {
  13. for b.Loop() {
  14. Builder(words)
  15. }
  16. })
  17. }
  18. }

執行:
  1. go test -bench=Builder -benchmem -benchtime=2000x

輸出:
  1. goos: darwin
  2. goarch: arm64
  3. pkg: example.com/join
  4. cpu: Apple M5
  5. BenchmarkBuilder/n=10-10 2000 101.5 ns/op 56 B/op 3 allocs/op
  6. BenchmarkBuilder/n=100-10 2000 740.7 ns/op 504 B/op 6 allocs/op
  7. BenchmarkBuilder/n=1000-10 2000 5848 ns/op 5368 B/op 10 allocs/op
  8. PASS
  9. 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 數字因機器而異,只比較同一台機器上的相對差異

資料來源