打赏

golang性能分析

golang性能分析

go-torch 使用

1.)安装graphviz

apt intstall graphviz

2.)安装go-torch

go get github.com/uber/go-torch
下载并复制flamegraph.pl到$GOPATH/bin下
https://github.com/brendangregg/FlameGraph

输出prof到文件

通过调用runtime/pprof的API实现。go支持多种Profile,可以用go help testflag查看。
(1.)代码中插入输出cpu、mem的代码块

// 获取CPU信息
func main(){
    // 创建输出文件
    f,_ := os.Create("cpu.prof")
    defer f.Close()
    // 获取系统信息
    _ := pprof.StartCPUProfile(f)

    defer pprof.StopCPUProfile()
}

// 获取内存信息
func main(){
    // 创建输出文件
    f,_ := os.Create("mem.prof")
    // 获取系统信息
    _ := pprof.WriteHeapProfile(f)
    f1.Close()

    // 查看goroutine
    f1,_ := os.Create("goroutine.prof")
    gProf := pprof.Lookup("goroutine");
    gProf.WriteTo(f1,0)
    defer f1.Close()
}

(2.)编译运行后会自动输出对应的文件

go build xx.go  //生成二进制文件
./xx  // 运行二进制文件

// 使用pprof工具查看
go tool pprof prof cpu.prof  // 查看Cpu的性能数据,输入top,可以查看前十个占用cpu的代码块,可以使用list 方法名  查看具体某个方法占用的内存,执行时间等

// 或者使用go-torch查看
go-torch cpu.prof  // top
# 下载cpu profile,默认从当前开始收集30s的cpu使用情况,需要等待30s
go tool pprof http://localhost:9527/debug/pprof/profile   # 30-second CPU profile
go tool pprof http://localhost:9527/debug/pprof/profile?seconds=120     # wait 120s

# 下载heap profile
go tool pprof http://localhost:9527/debug/pprof/heap      # heap profile

# 下载goroutine profile
go tool pprof http://localhost:9527/debug/pprof/goroutine # goroutine profile

# 下载block profile
go tool pprof http://localhost:9527/debug/pprof/block     # goroutine blocking profile

# 下载mutex profile
go tool pprof http://localhost:9527/debug/pprof/mutex

详细内容,可查看: https://golang.org/src/runtime/pprof/pprof.go

使用HTTP的方式输出Profile

1.)在应用程序中导入pprof包,并启动http server

import _ "net/http/pprof"

2.) 查看界面

http://IP:Port/debug/pprof

3.) 也可以通过pprof工具查看

go tool pprof _http://IP:PORT/debug/pprof/profile?seconds=10   // top -cum |  list xxx  | exit

go-torch seconds 10 http://IP:PORT/debug/pprof/profile

使用go test bench测试

go test -bench=.
go test -bench=. -cpuprofile=cpu.prof  // top -cum  | list xx | exit
posted @ 2021-04-17 22:55  苍山落暮  阅读(314)  评论(0编辑  收藏  举报