Go中使用profile有两种方式:
(1)使用离线的profile文件(import “runtime/pprof”),要保存CPU的profile数据,可使用以下代码:
f, err := os.Create("cpu_profile")
...
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
另一个是内存的profile数据:
f, err := os.Create("mem_profile")
pprof.WriteHeapProfile(f)
f.Close()
编译main.go文件生成main、cpu_profile、mem_profile,在当前目录下执行:
go tool pprof main cpu_profile
go tool pprof main mem_profile
在profile交互界面经常使用的命令 web, top, peek, list,可帮助我们查看程序运行相关的统计信息
(2)使用在线http服务进行分析(import _ “net/http/pprof”),引入之后代码执行了:
func init() {
http.HandleFunc("/debug/pprof/", Index)
http.HandleFunc("/debug/pprof/cmdline", Cmdline)
http.HandleFunc("/debug/pprof/profile", Profile)
http.HandleFunc("/debug/pprof/symbol", Symbol)
http.HandleFunc("/debug/pprof/trace", Trace)
}
因此, 我们在main函数中监听某个端口
http.ListenAndServe(":8080", nil)
再执行
go tool pprof main http://localhost/debug/pprof/profile
想要获取内存信息,可将命令改为:
go tool pprof main http://localhost/debug/heap/profile