go test benchmark


Benchtest的簡單使用

一個簡單的benchtest用例

// 以BenchmarkXXX類似命名,並傳入b *testing.B 參數
func BenchmarkLoopSum(b *testing.B) {
    for i := 0; i < b.N; i++ {
        total := 0
        for j := 0; j <= maxLoop; j++ {
            total += j
        }
    }
}

查看benchtest的參數: go help testflag
-bench grep
通過正則表達式過濾出需要進行benchtest的用例
-count n
跑n次benchmark,n默認為1
-benchmem
打印內存分配的信息
-benchtime=5s
自定義測試時間,默認為1s

測試命令:$ go test --bench=LoopSum my_test.go -benchmem
運行結果:

goos: windows
goarch: amd64
BenchmarkLoopSum-12         5000            316952 ns/op               0 B/op          0 allocs/op
PASS
ok      command-line-arguments  1.939s

5000表示測試次數,即test.B提供的N, ns/op表示每一個操作耗費多少時間(納秒)。B/op表示每次調用需要分配16個字節。allocs/op表示每次調用有多少次分配
基准測試框架對一個測試用例的默認測試時間是 1 秒。開始測試時,當以 Benchmark 開頭的基准測試用例函數返回時還不到 1 秒,那么 testing.B 中的 N 值將按 1、2、5、10、20、50……遞增,同時以遞增后的值重新調用基准測試用例函數。

$ go test --bench=. my_test.go -benchmem
goos: windows
goarch: amd64
BenchmarkRange-12                 100000             20505 ns/op               8 B/op          0 allocs/op
BenchmarkFor-12                  1000000              2054 ns/op               0 B/op          0 allocs/op
BenchmarkLoopSum-12                 5000            315755 ns/op               0 B/op          0 allocs/op
BenchmarkLoopRecursion-12            300           4664190 ns/op               0 B/op          0 allocs/op
PASS
ok      command-line-arguments  8.792s


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM