基本用法#

func BenchmarkFibonacci(b *testing.B) {
    // b.N 由測試框架動態決定
    // 會自動調整直到執行時間穩定
    for i := 0; i < b.N; i++ {
        Fibonacci(20)
    }
}

執行基準測試:

# 執行所有基準測試
go test -bench=.

# 只執行特定基準測試
go test -bench=BenchmarkFibonacci

# 設定執行時間
go test -bench=. -benchtime=5s

# 包含記憶體分配統計
go test -bench=. -benchmem

輸出格式#

BenchmarkFibonacci-8    1000000    1052 ns/op    0 B/op    0 allocs/op
                   │         │           │          │              │
                   │         │           │          │              └─ 每次操作的記憶體配置次數
                   │         │           │          └─ 每次操作配置的位元組數
                   │         │           └─ 每次操作的奈秒數
                   │         └─ 執行次數
                   └─ CPU 核心數

進階用法#

// 重置計時器(排除設定時間)
func BenchmarkWithSetup(b *testing.B) {
    data := generateLargeData()  // 設定
    b.ResetTimer()               // 重置計時器

    for i := 0; i < b.N; i++ {
        processData(data)
    }
}

// 停止/開始計時器
func BenchmarkWithPause(b *testing.B) {
    for i := 0; i < b.N; i++ {
        b.StopTimer()
        input := prepareInput()  // 不計入
        b.StartTimer()

        process(input)  // 只計這部分
    }
}

// 報告自訂指標
func BenchmarkThroughput(b *testing.B) {
    data := make([]byte, 1024)
    b.SetBytes(1024)  // 設定每次操作處理的位元組數

    for i := 0; i < b.N; i++ {
        processBytes(data)
    }
}
// 輸出會包含 MB/s 指標

並行基準測試#

func BenchmarkParallel(b *testing.B) {
    b.RunParallel(func(pb *testing.PB) {
        // 每個 goroutine 執行
        for pb.Next() {
            ConcurrentOperation()
        }
    })
}

RunParallel 會根據 GOMAXPROCS 啟動對應數量的 goroutine。這對測試併發程式碼的效能特別有用。