Go 语言性能分析

1. 准备工作#

1.1 下载 go-wrk#

这个是用来进行 http 接口压测的
官网地址:https://github.com/tsliwowicz/go-wrk
七牛云下载

使用

go-wrk -d 500 http://localhost:8080/hello

1.2 安装生成火焰图工具#

1.2.1 下载 go-torch#

go get github.com/uber/go-torch

1.2.2 安装 perl#

官网下载地址:https://www.activestate.com/products/perl/...
七牛云下载
注意:安装时记得把添加到环境变量 PATH 选项勾上

1.2.3 下载 FlameGraph#

git clone https://github.com/brendangregg/FlameGraph.git

注意:将此文件夹加入到 PATH 环境变量中

1.3 下载 graphviz#

生成 SVG 图,能够更好地看到函数调用 CPU 占用情况

1.3.1 Windows 安装#

官网下载地址:https://graphviz.gitlab.io/_pages/Download...
七牛云下载
安装好之后,添加其 bin 文件到 PATH 环境变量中

1.3.2 Linux 安装#

# Ubuntu
sudo apt-get install graphviz

# Centos
yum install graphviz

1.3.3 测试#

检查是否安装成功

dot -version

2. 性能分析#

2.1 开启性能分析#

开启性能分析只需要导入下面这个包即可

import _ "net/http/pprof"

2.2 开始压测#

代码见文章末尾附录

  1. 启动 main.go
  2. 开始压测
    go-wrk -d 500 http://localhost:8080/hello

2.3 web 查看#

浏览器打开:http://localhost:8080/debug/pprof/

  • allocs: 内存分配情况
  • block: 导致阻塞同步的堆栈跟踪
  • cmdline: 当前程序激活的命令行
  • goroutine: 当前运行的 goroutine
  • heap: 存活对象的内存分配情况
  • mutex: 互斥锁的竞争持有者的堆栈跟踪
  • profile: 默认进行 30s 的 CPU Profiling
  • threadcreate: 操作系统线程跟踪
  • trace: 当前程序执行情况
  • full goroutine stack dump: 所有 goroutine 栈输出

    2.4 采样分析#

    下面命令会打开一个交互页面

    go tool pprof --seconds 5 http://localhost:8080/debug/pprof/profile

    常用命令

  • top 默认显示 10 个占用 CPU 时间最多的函数
  • tree 树形结构查看 goroutine 情况。
  • web 生成 SVG 函数调用图(需安装 graphviz
  • exit 退出分析

打开 pprof 可视化页面,与上面 可交互页面中 web 命令效果一样

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

2.5 生成火焰图#

进行 5 秒钟的 CPU 性能采样并生成火焰图

go-torch --seconds 5 http://localhost:8080/debug/pprof/profile

命令执行完会在该目录下生成一个 torch.svg 文件,可用浏览器打开查看火焰图

3. Go 压力测试分析#

  1. 生成 pprof.cpu 文件
    go test -bench . -benchmem -cpuprofile pprof.cpu
  2. 分析 pprof.cpu 文件
    go tool pprof pprof.cpu

代码#

https://github.com/pibigstar/go-demo/tree/...

本作品采用《CC 协议》,转载必须注明作者和本文链接