假如你發現服務 cpu / 內存佔用率過高,或是請求響應慢,你想知道是哪段代碼出了問題,pprof 就是用來幫你幹這個的。
- 首先要提前引入 pprof 庫,很簡單,就在服務端代碼的基礎上多加幾行代碼
import (
"net/http"
_ "net/http/pprof"
)
func main() {
go func() {
http.ListenAndServe("localhost:8080", nil)
}()
// 主進程
}
- 點擊下圖裡的 profile,會採集 30s 的數據保存到 profile 文件裡
之後運行
go tool pprof -http :8081 ./profile
- 打開
http://localhost:8081/ui/
左上角可以選擇傳說的火焰圖 (Flame Graph):