Go语言的性能分析工具pprof怎么用

2023-05-21,

今天就跟大家聊聊有关Go语言的性能分析工具pprof怎么用,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

一、pprof的概述:

pprof:是Go的性能分析工具,在程序运行过程中,可以记录程序的运行信息,可以是CPU使用情况、内存使用情况、goroutine运行情况等,Go语言已经将pprof 封装在包net/http/pprof中。

对于pprof来说主要用于:CPU分析、内存分析、阻塞分析、互斥锁分析。

查看这些指标有两种方式,一种是浏览器方式,一种是命令行方式。

浏览器方式:

通过 http://pprofIPAddress:port/debug/pprof/ 来访问,访问之后的界面如下所示:

命令行方式:

基本命令:

# 下载cpu profile,默认从当前开始收集30s的cpu使用情况,需要等待30sgo tool pprof http://localhost:6060/debug/pprof/profile# 30-second CPU profile go tool pprof http://localhost:6060/debug/pprof/profile?seconds=120# wait 120s# 下载heap profile go tool pprof http://localhost:6060/debug/pprof/heap# heap profile# 下载goroutine profile go tool pprof http://localhost:6060/debug/pprof/goroutine# goroutine profile# 下载block profile go tool pprof http://localhost:6060/debug/pprof/block# goroutine blocking profile# 下载mutex profile go tool pprof http://localhost:6060/debug/pprof/mutex

本篇文章算是pprof的入门篇章,主要讲解CPU分析和内存分析两部分的使用方法。

二、内存分析:

这里的内存指的是Go中的堆数据,例子如下所示:

package mainimport (    "fmt"    "time"    "sync"    "net/http"    _ "net/http/pprof")
var buf []bytefunc Add() {    tick := time.Tick(time.Second / 200)    for range tick {        buf = append(buf, make([]byte, 2*1024*1024)...)    }}func main() {    // 开启pprof,监听请求    var wg sync.WaitGroup    wg.Add(1)    go func() {        defer wg.Done()        ip := "0.0.0.0:6060"        if err := http.ListenAndServe(ip, nil); err != nil {            fmt.Printf("start pprof failed on %s\n", ip)        }    }()    fmt.Println("continue~")    Add()    wg.Wait()}

通常分析内存信息,需要使用go tool pprof http://localhost:6060/debug/pprof/heap,一般采样多次进行比较,看内存的变化。而查看内存信息,主要用到pprof中的三个命令top、list 和traces, 如下所示:

step 1: 生成两个内存分析文件,这两个时间间隔取决于自己的需要,本例间隔差不多1分30秒。

step 2: 比较两个内存文件中的区别。

$go tool pprof -base ~/pprof/pprof.alloc_objects.alloc_space.inuse_objects.inuse_space.001.pb.gz ~/pprof/pprof.alloc_objects.alloc_space.inuse_objects.inuse_space.002.pb.gz

-base:表示的是以第一个内存文件作为比较样本。

step 3: 分析内存信息。

通过top、list和traces来查看内存信息。通过下面的执行结果,我们可以看出来,mian.Add函数使用的内存最多,而在Add中14行的buf = append(buf,make([]byte),2*1024*1024)是新增内存的来源。

对于traces来讲,.........之间表示的是一个堆栈的调用关系。

备注:对于float、cum的介绍如下所示:

cum          Sort entries based on cumulative weight

 flat            Sort entries based on own weight

三、CPU分析:

对于CPU的使用分析要比内存简单一些,毕竟CPU不需要分成几块进行比较,分析步骤如下:

step 1: 采集cpu数据信息。

命令:$ go tool pprof http://localhost:6060/debug/pprof/profile

step 2: 分析CPU信息。

通过top、list、traces来进一步进行分析CPU的热点。

top和list 来查看cpu的使用时间:

traces分析:

看完上述内容,你们对Go语言的性能分析工具pprof怎么用有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注本站行业资讯频道,感谢大家的支持。