天天看点

Go pprof性能调优

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的总耗时百分比

最后一列:调用函数名称