(十五)golang pprof

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

支持什么使用模式
Report generation:报告生成
Interactive terminal use:交互式终端使用
Web interface:Web 界面

package main

import (
    "fmt"
    "log"
    "net/http"
    _ "net/http/pprof" //执行init函数
    "strings"
)

func sayhelloName(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()       //解析参数,默认是不会解析的
    fmt.Println(r.Form) //这些信息是输出到服务器端的打印信息
    fmt.Println("path", r.URL.Path)
    fmt.Println("scheme", r.URL.Scheme)
    fmt.Println(r.Form["url_long"])
    for k, v := range r.Form {
        fmt.Println("key:", k)
        fmt.Println("val:", strings.Join(v, ""))
    }
    fmt.Fprintf(w, "Hello Wrold!") //这个写入到w的是输出到客户端的
}
func main() {
    http.HandleFunc("/", sayhelloName)       //设置访问的路由
    err := http.ListenAndServe(":9090", nil) //设置监听的端口
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

一、通过 Web 界面
可以访问http://127.0.0.1:9090/debug/pprof/来查看各种信息。

B007709B-CABC-4C27-A7F3-B81F530A37F0.png

cpu(CPU Profiling): http://127.0.0.1:9090/debug/pprof/profile,默认进行 30s 的 CPU Profiling,得到一个分析用的 profile 文件
block(Block Profiling):http://127.0.0.1:9090/debug/pprof/block,查看导致阻塞同步的堆栈跟踪
goroutine:http://127.0.0.1:9090/debug/pprof/goroutine,查看当前所有运行的 goroutines 堆栈跟踪
heap(Memory Profiling): http://127.0.0.1:9090/debug/pprof/heap,查看活动对象的内存分配情况
mutex(Mutex Profiling):http://127.0.0.1:9090/debug/pprof/mutex,查看导致互斥锁的竞争持有者的堆栈跟踪
threadcreate:$HOST/debug/pprof/threadcreate,查看创建新OS线程的堆栈跟踪
二、通过交互式终端使用

go tool pprof http://127.0.0.1:9090/debug/pprof/profile

30秒后进入pprof的交互模式,然后输入

web

然后浏览器自动弹开到网页展示svg图(安装过graphviz)
输入

top10
E1749188-9B89-4220-814A-99D15DA07F43.png

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

go tool pprof http://127.0.0.1:9090/debug/pprof/heap

-inuse_space:分析应用程序的常驻内存占用情况

-alloc_objects:分析应用程序的内存临时分配情况
三、PProf 可视化界面
需要test支持

go test -bench . -cpuprofile cpu.out
go tool pprof -http=:8080 cpu.out
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 原文地址:Golang 大杀器之性能剖析 PProf 前言 写了几吨代码,实现了几百个接口。功能测试也通过了,终于...
    EDDYCJY阅读 73,127评论 7 78
  • 基本路径:/debug/pprof/ 支持的分析类型: cpu(CPU Profiling) : ...
    凯文不上班阅读 1,648评论 0 0
  • 概述 pprof 是用于可视化和分析性能分析数据的工具CPU Profiling:CPU 分析,按照一定的频率采集...
    _羊羽_阅读 485评论 0 0
  • 今天听了十分钟的财富课,脑洞飞翻。 看到在我们的城市,公交卡办卡、充值、老年卡年检、学生卡办理需要文件,要到充值点...
    斐狐阅读 369评论 0 1
  • 理解D3中的Update、Enter、Exit解决的问题是选择集跟数据的数量不对等的情况,下面这段代码中selec...
    黄清淮阅读 2,973评论 0 0