1. 程式人生 > 實用技巧 >Go 基準測試和效能測試學習使用

Go 基準測試和效能測試學習使用

Go 效能測試

基準測試

基準測試主要是通過測試CPU和記憶體的效率問題,來評估被測試程式碼的效能,進而找到更好的解決方案。

  1. 基準測試的程式碼檔案必須以_test.go結尾
  2. 基準測試的函式必須以Benchmark開頭,必須是可匯出的
  3. 基準測試函式必須接受一個指向Benchmark型別的指標作為唯一引數
  4. 基準測試函式不能有返回值
  5. b.ResetTimer是重置計時器,這樣可以避免for迴圈之前的初始化程式碼的干擾
  6. 最後的for迴圈很重要,被測試的程式碼要放到迴圈裡
  7. b.N是基準測試框架提供的,表示迴圈的次數,因為需要反覆呼叫測試的程式碼,才可以評估效能

命令如下

go test -bench=.
# -bench=標記,接受一個表示式作為引數, .表示執行所有的基準測試。可以只寫方法名字,挑選基準測試

go test -bench=. -run=none
# -run=匹配一個從來沒有的單元測試方法,過濾掉單元測試的輸出,我們這裡使用none,因為我們基本上不會建立這個名字的單元測試方法。因為預設情況下 go test 會執行單元測試,為了防止單元測試的輸出影響我們檢視基準測試的結果.

goos: darwin
goarch: amd64
pkg: github.com/devhg/LearnGo/benchmark/strcontact
//Benchmark名字-CPU        迴圈次數          平均每次執行時間
BenchmarkAdd-8              5223            212483 ns/op
BenchmarkFormat-8           3456            353151 ns/op
BenchmarkBuffer-8         129862              8876 ns/op
BenchmarkBuilder-8        157110              6456 ns/op
BenchmarkAppend-8          86055             13071 ns/op
PASS
ok      github.com/devhg/LearnGo/benchmark/strcontact   7.559s

//看到函式後面的-8了嗎?這個表示執行時對應的GOMAXPROCS的值。
//迴圈次數:執行for迴圈的次數也就是呼叫被測試程式碼的次數
//平均每次執行時間:執行一次操作花費的時間

測試時間預設是1秒,也就是1秒的時間呼叫次數,我們可以通過以下修改。

go test -bench=. -benchtime=3s -run=none
# 可以通過-benchtime指定時間

效能對比

-benchmem可以提供每次操作分配記憶體的次數,以及每次操作分配的位元組數。

go test -bench=. -benchmem -run=none
# -benchmem可以提供每次操作分配記憶體的次數,以及每次操作分配的位元組數。
goos: darwin
goarch: amd64
pkg: github.com/devhg/LearnGo/benchmark/strcontact
BenchmarkAdd-8              5299            248707 ns/op         1063894 B/op        999 allocs/op
BenchmarkFormat-8           3362            358401 ns/op         1096746 B/op       3000 allocs/op
BenchmarkBuffer-8         129304              8602 ns/op            6576 B/op          7 allocs/op
BenchmarkBuilder-8        162169              6431 ns/op            7416 B/op         11 allocs/op
BenchmarkAppend-8          87915             13102 ns/op            9464 B/op         12 allocs/op
PASS
ok      github.com/devhg/LearnGo/benchmark/strcontact   9.539s

在程式碼開發中,對於我們要求效能的地方,編寫基準測試非常重要,這有助於我們開發出效能更好的程式碼。不過效能、可用性、複用性等也要有一個相對的取捨,不能為了追求效能而過度優化。

結合pprof效能監控

go test -bench=. -benchmem -cpuprofile profile.out
# 生成cpu profile
go test -bench=. -benchmem -memprofile memprofile.out -cpuprofile profile.out
# 同時生成cpu和記憶體 profile

使用pprof工具檢視

go tool pprof profile.out
go tool pprof memprofile.out
go tool pprof -http=":8081" [binary] [profile]

報錯:Failed to execute dot. Is Graphviz installed? Error: exec: "dot": executable file not found in %PATH%

是你電腦沒有安裝gvedit導致的

fq進入gvedit官網https://graphviz.gitlab.io/_pages/Download/Download_windows.html 下載穩定版

mac 安裝, 安裝好後就可以使用web進行展現了

brew install graphviz

https://my.oschina.net/solate/blog/3034188