Golang 中监控代码性能的有两个包
- net/http/pprof
- runtime/pprof
runtime/pprof简单用法:
1、代码中添加
import "flag"
import "runtime/pprof"
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile `file`")
var memprofile = flag.String("memprofile", "", "write memory profile to `file`")
在需要添加的函数开头加入:
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal("could not create CPU profile: ", err)
}
if err := pprof.StartCPUProfile(f); err != nil { //监控cpu
log.Fatal("could not start CPU profile: ", err)
}
defer pprof.StopCPUProfile()
}
函数结尾加入:
if *memprofile != "" {
f, err := os.Create(*memprofile)
if err != nil {
log.Fatal("could not create memory profile: ", err)
}
runtime.GC() // GC,获取最新的数据信息
if err := pprof.WriteHeapProfile(f); err != nil { // 写入内存信息
log.Fatal("could not write memory profile: ", err)
}
f.Close()
}
2、编译运行
编译完成,运行时加入参数:
./org_client -conf ../conf/trpc_go.yaml --cpuprofile=cpu.prof --memprofile=mem.prof
3、调用完成可以看到本地文件中多了两个文件:
4、运行分析工具:
运行命令 go tool pprof cpu.prof
然后就可以输入help查看具体命令和参数了