美文网首页
go 的性能分析工具 pprof

go 的性能分析工具 pprof

作者: wayyyy | 来源:发表于2021-11-21 02:48 被阅读0次

pprof 功能有2种开启方式,对应两种包:

  • net/http/pprof:使用服务器的场景
  • runtime/pprof:使用在非服务器应用程序的场景

这两个本质上是一致的,net/http/pporf 也只是在 runtime/pprof 上的一层 web 封装

pprof 支持四种类型的分析:

  • CPU
    CPU 分析,采样消耗 cpu 的调用,这个一般用来定位排查程序里耗费计算资源的地方。
  • Memory
    内存分析,一般用来排查内存占用,内存泄露等问题。
  • Block
    阻塞分析,会采样程序里阻塞的调用情况。
  • Mutex
    互斥锁分析,采样互斥锁的竞争情况。
一个简单的例子
package main

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

var datas []string

func add(s string) []string {
    datas = append(datas, s)
    return datas
}

func main() {
    go func() {
        for {
            fmt.Println(add("hello world"))
        }
    }()

    http.ListenAndServe("0.0.0.0:6060", nil)
}

直接web访问:http://127.0.0.1:6060/debug/pprof/

image.png

需要注意的是:默认情况下是不会追踪 block 和 mutex 信息的,如果想要看这2个信息,需要在代码中加入:

runtime.SetBlockProfileRate(1) // 开启对阻塞操作的跟踪,block  
runtime.SetMutexProfileFraction(1) // 开启对锁调用的跟踪,mutex
分析数据

通过网页看到的信息有限,更常规的做法是把数据下载下来,更专业的分析。

# 下载 cpu profile
go tool pprof http://127.0.0.1:6060/debug/pprof/profile

# 下载 heap profile
# go tool pprof http://47.93.238.9:8080/debug/pprof/heap

# 下载 goroutine profile
# go tool pprof http://47.93.238.9:8080/debug/pprof/goroutine

# 下载 block profile
# go tool pprof http://47.93.238.9:8080/debug/pprof/block

# 下载 mutex profile
# go tool pprof http://47.93.238.9:8080/debug/pprof/mutex

linux 下还可以使用:

# 这里以生成 trace.out 文件为例:
curl localhost:/debug/pprof/trace?seconds=30 > trace.out

运行上述命令将会让程序开始半分钟的cpu采样,并把内容保存到本地文件中:


image.png

接着我们可以输入一些命令,来获取一些信息:

  • top
    列出cpu占用高的函数


    image.png
  • traces
    列出函数调用栈


参考资料
1、Go语言之pprof的性能调优
2、https://mp.weixin.qq.com/s/SvzMEdhxHfI9hYU62r1C7g
3、https://zhuanlan.zhihu.com/p/396363069
4、https://zhuanlan.zhihu.com/p/265080950
5、

相关文章

  • Go语言性能调优工具——pprof

    Go语言性能调优工具——pprof Go语言对性能要求比较高,所以内置了调优工具pprof,本文简单介绍下工具的使...

  • pprof 的使用

    基本介绍 pprof 是在做性能优化前的性能分析工具。 安装: go get -u github.com/goog...

  • (十五)golang pprof

    Go 提供了性能分析工具链:runtime/pprof:采集程序(非 Server)的运行数据进行分析net/ht...

  • go 性能剖析 PProf

    PProf是什么 pprof 是用于可视化和分析性能分析数据的工具 pprof 以 profile.proto 读...

  • go 的性能分析工具 pprof

    pprof 功能有2种开启方式,对应两种包: net/http/pprof:使用服务器的场景 runtime/pp...

  • Golang 使用pprof分析性能

    参考Golang 使用pprof分析goweb的性能问题 go的pprof可以用来对服务的性能进行检测,其中net...

  • pprof接口隐藏/认证

    pprof是golang提供的性能分析工具,这里就不过多介绍了。 使用方式很简单,导入pprof包即可 pprof...

  • go语言性能分析工具pprof

    pprof支持两种方式记录性能 1、runtime/pprof 2、net/http/pprof ,两种方式均可分...

  • pprof 工具使用

    pprof golang pprof是golang的可视化和性能分析的工具。其提供了可视化的web页面,火焰图等更...

  • 【实践】WINDOWS下GOlang性能测试分析工具PProf&

    1.摘要 本文讲解在Windows 10操作系统VS Code集成环境下,如何使用GO语言的PProf工具进行性能...

网友评论

      本文标题:go 的性能分析工具 pprof

      本文链接:https://www.haomeiwen.com/subject/jzqpnltx.html