Go应用性能分析
程序性能分析是一个非常庞大的话题,自下而上涉及底层CPU、网络、I/O,上层的业务逻辑复杂度、算法性能等。同时性能分析也是容易被大家忽略的点,往往线上出现问题、服务超时才会着手排查。工欲善其事,必先利其器,本文介绍两种Golang性能分析工具:pprof和torch。
1、pprof
pprof是Golang官方自带的程序性能分析包,可以在net/http/pprof
、runtime/pprof
这两个地方引用,net/http/pprof
实际也调用了runtime/pprof
,并在http端口上暴露。
(1)服务程序
引入方式如下:
import _ "net/http/pprof"
demo代码如下
package main
import "net/http"
import _ "net/http/pprof"
func main() {
http.ListenAndServe(":8080", http.DefaultServeMux)
}
然后访问该链接 http://127.0.0.1:8080/debug/pprof/
可以看到当前web服务的状态,包括CPU占用情况和内存使用情况
(2)应用程序
这种场景下需要引入runtime/pprof
包,对CPU运行信息进行采样存储,比如
package main
import "runtime/pprof"
import "os"
import "log"
func main() {
f, err := os.Create("cpu.prof")
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
下一步需要使用pprof文件做出性能分析图
go tool pprof test.exe cpu.prof
然后输入web
命令生成svg文件,svg用浏览器打开可以看到调用链。如果提示"profile is empty"是由于程序使用了很少的内存,无法进行采样导致,可以修改runtime.MemProfileRate
降低采样率,运行前加上环境变量GODEBUG="memprofilerate=1"
。
2、torch
go-torch是Uber公司开源的一款针对Go语言程序的火焰图生成工具(https://github.com/uber/go-torch),能收集 stack traces,并把它们整理成火焰图,直观地程序给开发人员,很方便地分析Go的各个方法所占用的CPU的时间。
(1)安装FlameGraph
Stack trace visualizer:profile数据的可视化层工具
git clone https://github.com/brendangregg/FlameGraph.git
cp flamegraph.pl /usr/local/bin
(2)安装torch
go get -v github.com/uber/go-torch
(3)使用torch
go-torch命令用法非常多,比如
Usage:
go-torch [options] [binary] <profile source>
pprof Options:
/u, /url: Base URL of your Go program (default:
http://localhost:8080)
/suffix: URL path of pprof profile (default: /debug/pprof/profile)
/t, /seconds: Number of seconds to profile for (default: 30)
/pprofArgs: Extra arguments for pprof
Output Options:
/f, /file: Output file name (must be .svg) (default: torch.svg)
/p, /print Print the generated svg to stdout instead of writing to
file
/r, /raw Print the raw call graph output to stdout instead of
creating a flame graph; use with Brendan Gregg's flame
graph perl script (see
https://github.com/brendangregg/FlameGraph)
......
(4)demo
使用torch采样方式分析程序30s性能情况,结束后会生成torch.svg。
go-torch -u http://localhost:8080 -t 30
火焰图的y轴表示cpu调用方法的先后,x轴表示在每个采样调用时间内,方法所占的时间百分比,越宽代表占据cpu时间越多。
评论已关闭