pprof 使用教程

pprof是Golang内置的性能分析工具,用于查看Web应用和程序的运行状态。通过开启pprof,可以分析CPU、内存、goroutine等使用情况。开启pprof后,可以通过Web界面或交互命令行分析性能,例如检查goroutine泄漏、CPU和内存使用。通过`go tool pprof`命令,可以收集CPU或内存信息并进行深入分析。
摘要由CSDN通过智能技术生成

简介

pprof 是 golang 自带的性能分析工具,可以查看web应用的运行状态,分析程序CPU,内存,goroutine等使用情况。

golang 针对不同使用场景,提供了以下两种方式开启pprof性能分析

runtime/pprof:采集程序(非 Server)的运行数据进行分析
net/http/pprof:采集 HTTP Server 的运行时数据进行分析
  • 开启pprof,举个栗子
package main

import (
    "net/http"
    _ "net/http/pprof"
)

func main () {
    // 通过协程开启pprof数据采集
    go func(){
        _ = http.ListenAndServe("0.0.0.0:6060", nil)
    }()
    
    // 业务代码doSomeThing
    ...
}

通过嵌入以上代码,程序将会自动采集运行时指标。

  • 通过web界面分析

打开浏览器,访问http://127.0.0.1:6060/debug/pprof/

/debug/pprof/

Types of profiles available:
Count	Profile
10	allocs                 
0	block
0	cmdline
93	goroutine
10	heap
0	mutex
0	profile
12	threadcreate
0	trace
full goroutine stack dump

Profile Descriptions:
    allocs: 过去所有内存分配的采样
    block: 导致同步原语阻塞的堆栈跟踪
    cmdline: 当前程序的命令行调用
    goroutine: 所有当前goroutine的堆栈跟踪
    heap: 活动对象内存分配的采样
    mutex: 互斥锁的堆栈跟踪
    profile: CPU使用情况
    threadcreate: 导致创建新OS线程的堆栈跟踪 
    trace:当前程序的执行跟踪.

一般goroutine导致的内存泄露,goroutine 的count数值会异常偏大。

  • 通过交互命令分析

执行以下命令,等待60秒。pprof会采集CPU信息,结束后进入命令行模式

go tool pprof http://127.0.0.1:6060/debug/pprof/profile?seconds=60
Fetching profile over HTTP from http://127.0.0.1:8888/debug/pprof/profile?seconds=60
Saved profile in C:\Users\2837.GOLDENTECAD\pprof\pprof.samples.cpu.001.pb.gz
Type: cpu
Time: Oct 28, 2021 at 3:09pm (CST)
Duration: 1mins, Total samples = 30ms ( 0.05%)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof)

输入 web 命令,可在弹出的浏览器窗口看到cpu占用情况;
输入 pdf 命令,会生成一张pdf文件;
输入 top10,会显示前10 最消耗cpu的程序片断;

(pprof) top10
Showing nodes accounting for 30ms, 100% of 30ms total
Showing top 10 nodes out of 15
      flat  flat%   sum%        cum   cum%
      10ms 33.33% 33.33%       10ms 33.33%  runtime.checkTimers
      10ms 33.33% 66.67%       10ms 33.33%  runtime.lock2
      10ms 33.33%   100%       10ms 33.33%  sync.(*Pool).pin
...

description
    flat:给定函数上运行耗时
    flat%:同上的 CPU 运行耗时总比例
    sum%:给定函数累积使用 CPU 总比例
    cum:当前函数加上它之上的调用运行总耗时
    cum%:同上的 CPU 运行耗时总比例

执行以下命令, pprof会分析内存占用信息,并进入命令行模式

go tool pprof http://127.0.0.1:6060/debug/pprof/heap
Fetching profile over HTTP from http://127.0.0.1:8888/debug/pprof/heap
Saved profile in C:\Users\2837.GOLDENTECAD\pprof\pprof.alloc_objects.alloc_space.inuse_objects.inuse_space.001.pb.gz
Type: inuse_space
Time: Oct 28, 2021 at 3:15pm (CST)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof)

同上也可输入 web,pdf,top10 等命令查看具体信息

  • 参考:
https://segmentfault.com/a/1190000016412013
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值