(十五)golang pprof - Go语言中文社区

(十五)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
版权声明:本文来源简书,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://www.jianshu.com/p/b763a6e6b4fe
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-01-12 12:58:17
  • 阅读 ( 1116 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢