栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

pprof 使用教程

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

pprof 使用教程

简介

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:Users2837.GOLDENTECADpprofpprof.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:Users2837.GOLDENTECADpprofpprof.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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/903411.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号