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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值