go pprof火焰圖性能優化
火焰圖(flame graph)是性能分析的利器,在go1.1之前的版本我們需要藉助go-torch生成,在go1.1後go tool pprof集成了此功能,今天就來說說如何使用其進行性能優化
依賴
go version>=1.1
主題
直接擼代碼,下面代碼可能會有寫多餘操作,不過此處只是為了簡單演示優化過程:
package main
import (
"encoding/json"
"fmt"
"net/http"
_ "net/http/pprof"
"time"
)
func main() {
go func() {
for {
LocalTz()
doSomething([]byte(`{"a": 1, "b": 2, "c": 3}`))
}
}()
fmt.Println("start api server...")
panic(http.ListenAndServe(":8080", nil))
}
func doSomething(s []byte) {
var m map[string]interface{}
err := json.Unmarshal(s, &m)
if err != nil {
panic(err)
}
s1 := make([]string, 0)
s2 := ""
for i := 0; i < 100; i++ {
s1 = append(s1, string(s))
s2 += string(s)
}
}
func LocalTz() *time.Location {
tz, _ := time.LoadLocation("Asia/Shanghai")
return tz
}
在你啟動http server的地方直接加入導入: _ "net/http/pprof"
然後運行程序後,直接訪問: http://127.0.01:8080/debug/pprof/,可以看到go運行的信息:
/debug/pprof/
Types of profiles available:
Count Profile
55 allocs
0 block
0 cmdline
4 goroutine
55 heap
0 mutex
0 profile
10 threadcreate
0 trace
full goroutine stack dump
Profile Descriptions:
allocs: A sampling of all past memory allocations
block: Stack traces that led to blocking on synchronization primitives
cmdline: The command line invocation of the current program
goroutine: Stack traces of all current goroutines
heap: A sampling of memory allocations of live objects. You can specify the gc GET parameter to run GC before taking the heap sample.
mutex: Stack traces of holders of contended mutexes
profile: CPU profile. You can specify the duration in the seconds GET parameter. After you get the profile file, use the go tool pprof command to investigate the profile.
threadcreate: Stack traces that led to the creation of new OS threads
trace: A trace of execution of the current program. You can specify the duration in the seconds GET parameter. After you get the trace file, use the go tool trace command to investigate the trace.
使用生成火焰圖優化
- 獲取cpuprofile
獲取最近10秒程序運行的cpuprofile,-seconds參數不填默認為30。
go tool pprof pprof http://127.0.0.1:8080/debug/pprof/profile -seconds 10
等10s後會生成一個: pprof.samples.cpu.001.pb.gz文件
2. 生成火焰圖
go tool pprof -http=:8081 ~/pprof/pprof.samples.cpu.001.pb.gz
其中-http=:8081會啟動一個http服務,埠為8081,然後瀏覽器會彈出此文件的圖解: