啟用pprof分析
import (
"net/http"
_ "net/http/pprof"
)
func pprof() error {
if err := http.ListenAndServe("0.0.0.0:8080", nil); err != nil {
return err
}
return nil
}
func main() {
go pprof()
// order codes
}
獲取診斷報告進行分析
直接訪問 localhost:8080/debug/pprof 可以看到能獲取到的診斷報告
| 診斷報告類型 | 備注 |
|---|---|
| allocs | 內存分配采樣 |
| block | 導致阻塞的的同步語句堆棧信息, 但需要使用runtime.SetBlockProfileRate(1)開啟 |
| cmdline | 進程啟動的命令行參數 |
| goroutine | 當前所有goroutine的堆棧信息 |
| heap | 當前活動的對象內存分配采樣 |
| mutex | 持有鎖的堆棧信息 |
| profile | cpu的占用信息 |
| threadcreate | 導致操作系統創建新增的線程的堆棧信息 |
| trace | 當前程序執行的trace |
分析CPU占用
go tool pprof --http=0.0.0.0:8081 --seconds=10 localhost:8080/debug/pprof/profile
分析內存占用
go tool pprof --http=0.0.0.0:8081 localhost:8080/debug/pprof/heap
go tool pprof --http=0.0.0.0:8081 localhost:8080/debug/pprof/allocs
查看trace信息
wget -O trace.out localhost:8080/debug/pprof/trace
go tool trace --http=:8081 trace.out
