pprof (golang 性能监控与分析)

参考文章

https://blog.wolfogre.com/posts/go-ppof-practice/
https://www.cnblogs.com/yjf512/archive/2012/12/27/2835331.html
https://xguox.me/go-profiling-optimizing.html/
https://segmentfault.com/a/1190000016412013
https://github.com/google/pprof

示例代码

package main

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

var datas []string

func Add(str string) string {
    data := []byte(str)
    sData := string(data)
    datas = append(datas, sData)
    return sData
}

func main() {
    if true {
        go func() {
            for {
                    log.Println(Add("https://github.com/EDDYCJY"))
                }
        }()
        runtime.GOMAXPROCS(1)               // 限制 CPU 使用数,避免过载
        runtime.SetMutexProfileFraction(1)  // 开启对锁调用的跟踪
        runtime.SetBlockProfileRate(1)      // 开启对阻塞操作的跟踪
        http.ListenAndServe("0.0.0.0:6060", nil)
    }
    
}

pprof使用

阅读:https://blog.wolfogre.com/posts/go-ppof-practice/

浏览器查看

打开浏览器访问 http://localhost:6060/debug/pprof/
在这里插入图片描述

交互式终端

go tool pprof http://localhost:6060/debug/pprof/profile?seconds=60

在这里插入图片描述

可视化PDF

首先进入交互式终端,然后输入pdf命令,其他文件格式执行pprof help查看命令说明。
在这里插入图片描述
在这里插入图片描述

可视化火焰图

启动可视化界面的命令格式:

$ go tool pprof -http=":8081" [binary] [profile]

binary:可执行程序的二进制文件,通过go build命名生成
profile:protobuf格式的文件

go tool pprof http://localhost:6060/debug/pprof/profile?seconds=10

执行相应命令,在$GOPATH目录下会生成相应pb文件
在这里插入图片描述

启动可视化界面
在这里插入图片描述
go tool pprof -http=":8081" pprof.**.pb.gz
访问响应URL,即可查看火焰图

 curl http://localhost:8081/ui/flamegraph > flamegraph.html

在这里插入图片描述

block分析

报告协程阻塞的情况,可以用来分析和查找死锁等性能瓶颈,默认不开启, 需要调用runtime.SetBlockProfileRate开启。

扫描二维码关注公众号,回复: 8865042 查看本文章
go tool pprof http://ip:port/debug/pprof/block

协程分析

报告协程相关信息,可以用来查看有哪些协程正在运行、有多少协程在运行等。

go tool pprof http://ip:port/debug/pprof/goroutine

heap 分析

heap:查看堆相关信息,包括一些GC的信息。

go tool pprof http://ip:port/debug/pprof/heap

mutex 分析

查看互斥的争用情况,默认不开启, 需要调用需要在程序中调用runtime.SetMutexProfileFraction。

发布了88 篇原创文章 · 获赞 317 · 访问量 35万+

猜你喜欢

转载自blog.csdn.net/sunxianghuang/article/details/93869683