前面 2 篇 golang 性能優化分析系列文章:html
在 golang 中,能夠經過 benchmark 基準測試來測試代碼性能。基準測試主要是經過測試 cpu 和內存的效率問題,來評估被測試代碼的性能。golang
基準測試的指標:web
基準測試文件名和函數規定:正則表達式
_test.go
結尾,和單元測試用例在同一個文件中。Benchmark
開頭。基準測試經常使用命令:瀏覽器
go test ./fib // 不進行基準測試,對 fib 進行單元測試 go test -bench=. -run=none // 進行基準測試,不進行單元測試,-run 表示執行哪些單元測試和測試函數,通常函數名不會是 none,因此不執行單元測試 // 上面的測試命令還能夠用空格隔開,意義是同樣 go test -bench . -run none go test -bench=. // 對全部的進行基準測試 go test -bench='fib$' // 只運行以 fib 結尾的基準測試,-bench 能夠進行正則匹配 go test -bench=. -benchtime=6s // 基準測試默認時間是 1s,-benchtime 能夠指定測試時間 go test -bench=. -benchtime=50x // 參數 -benchtime 除了指定時間,還能夠指定運行的次數 go test -bench=. -benchmem // 進行時間、內存的基準測試
說明:上面的命令中,
-bench
後面都有一個.
,這個點並非指當前文件夾,而是一個匹配全部測試的正則表達式。性能優化
更多參數說明請查看幫助:
go help testflag
函數
分析基準測試數據:工具
在配合 pprof 就能夠進行分析。性能
運行命令採樣數據:單元測試
go test -bench=. -run=none -benchmem -memprofile=mem.pprof go test -bench=. -run=none -blockprofile=block.pprof go test -bench=. -run=none -benchmem -memprofile=mem.pprof -cpuprofile=cpu.pprof
fib.go:
package main func Fib(n int) int { if n < 2 { return n } return Fib(n-1) + Fib(n-2) }
fib_test.go:
package main import ( "testing" ) func BenchmarkFib(b *testing.B) { // 運行 Fib 函數 b.N 次 for n := 0; n < b.N; n++ { Fib(20) } } func BenchmarkFib2(b *testing.B) { // 運行 Fib 函數 b.N 次 for n := 0; n < b.N; n++ { Fib(10) } }
go test -bench=. -run=none \ -benchmem -memprofile=mem.pprof \ -cpuprofile=cpu.pprof \ -blockprofile=block.pprof
也能夠用一個一個命令來完成採集數據,分開運行:
go test -bench=. -run=none -benchmem -memprofile=mem.pprof
go test -bench=. -run=none -benchmem -cpuprofile=cpu.pprof
前面有 上,下 兩篇 pprof 的文章怎麼分析數據,一種方法是命令行交互分析模式,一種是可視化圖形分析模式。
A. 命令行交互分析
分析 cpu:
go tool pprof cpu.pprof
再用
top15
命令分析,或者top --cum
進行排序分析
以下圖:
B. web 界面分析
命令行執行命令:
go tool pprof -http=":8080" cpu.pprof
會自動在瀏覽器上打開地址:http://localhost:8080/ui/ ,而後就能夠在瀏覽器上查看各類分析數據,以下圖:
其餘數據也能夠進行一樣的分析,這裏就略過。
[完]