pprof檔案作用
從樣本記錄中分析出代碼計算時間最長或者說最耗CPU資源的部分,可以通過以下代碼啟動對CPU使用情況的記錄
import "runtime/pprof"
func startCPUProfile(cpuProfile string) {
if cpuProfile != "" {
f, err := os.Create(cpuProfile)
if err != nil {
fmt.Fprintf(os.Stderr, "Can not create cpu profile output file: %s",err)
return
}
if err := pprof.StartCPUProfile(f); err != nil {
fmt.Fprintf(os.Stderr, "Can not start cpu profile: %s", err)
f.Close()
return
}
}
defer pprof.StopCPUProfile()
}
func main() {
xxx //主體函數
var cpuProfile "cpu.prof"
startCPUProfile(cpuProfile)
}
使用如下指令對CPU檔案進行了檢視和分析,可以試着對記憶體概要檔案和程式阻塞概要檔案進行分析
go tool pprof cpu.pprof
執行上面的代碼會進入互動界面如下:
root$ go tool pprof cpu.pprof
Entering interactive mode (type "help" for commands, "o" for options)
(pprof)
我們可以在互動界面輸入top3來檢視程式中占用CPU前3位的函數:
(pprof) top3
Showing nodes accounting for 100.37s, 87.68% of 114.47s total
Dropped 17 nodes (cum <= 0.57s)
Showing top 3 nodes out of 4
flat flat% sum% cum cum%
42.52s 37.15% 37.15% 91.73s 80.13% runtime.xxx
35.21s 30.76% 67.90% 39.49s 34.50% runtime.xxx
22.64s 19.78% 87.68% 114.37s 99.91% main.xxx
flat:目前函數占用CPU的耗時
flat%::目前函數占用CPU的耗時百分比
sun%:函數占用CPU的耗時累計百分比
cum:目前函數加上調用目前函數的函數占用CPU的總耗時
cum%:目前函數加上調用目前函數的函數占用CPU的總耗時百分比
最後一列:調用函數名稱