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的总耗时百分比
最后一列:调用函数名称

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值