Open guanhui07 opened 2 years ago
类似 php的xhprof
想度量这个应用程序的 CPU 性能数据, 只需要在 main 函数中添加 2 行代码即可:
pprof.StartCPUProfile(os.Stdout) defer pprof.StopCPUProfile()
go run main.go > cpu.pprof
一般不建议将结果直接输出到标准输出,因为如果程序本身有输出,则会相互干扰,直接记录到一个文件中是最好的方式。
func main() { f, _ := os.OpenFile("cpu.pprof", os.O_CREATE|os.O_RDWR, 0644) defer f.Close() pprof.StartCPUProfile(f) defer pprof.StopCPUProfile() n := 10 for i := 0; i < 5; i++ { nums := generate(n) bubbleSort(nums) n *= 10 } }
只需运行 go run main.go即可。
go run main.go
接下来,可以用 go tool pprof 分析这份数据
$ go tool pprof -http=:9999 cpu.pprof
提示 Graphviz 没有安装,则通过 brew install graphviz(MAC) 或 apt install graphviz(Ubuntu) 即可。
然后访问问 localhost:9999,可以看到分析图页面:
除了在网页中查看分析数据外,我们也可以在命令行中使用交互模式查看。
$ go tool pprof cpu.pprof File: main Type: cpu Time: Nov 19, 2020 at 1:43am (CST) Duration: 16.42s, Total samples = 14.26s (86.83%) Entering interactive mode (type "help" for commands, "o" for options) (pprof) top Showing nodes accounting for 14.14s, 99.16% of 14.26s total Dropped 34 nodes (cum <= 0.07s) flat flat% sum% cum cum% 14.14s 99.16% 99.16% 14.17s 99.37% main.bubbleSort 0 0% 99.16% 14.17s 99.37% main.main 0 0% 99.16% 14.17s 99.37% runtime.main
看到 main.bubbleSort 是消耗 CPU 最多的函数。
https://segmentfault.com/a/1190000016412013
https://www.cnblogs.com/Dr-wei/p/11742414.html
https://xargin.com/pprof-and-flamegraph/
类似 php的xhprof
想度量这个应用程序的 CPU 性能数据, 只需要在 main 函数中添加 2 行代码即可:
一般不建议将结果直接输出到标准输出,因为如果程序本身有输出,则会相互干扰,直接记录到一个文件中是最好的方式。
只需运行
go run main.go
即可。接下来,可以用 go tool pprof 分析这份数据
提示 Graphviz 没有安装,则通过 brew install graphviz(MAC) 或 apt install graphviz(Ubuntu) 即可。
然后访问问 localhost:9999,可以看到分析图页面:
除了在网页中查看分析数据外,我们也可以在命令行中使用交互模式查看。
看到 main.bubbleSort 是消耗 CPU 最多的函数。
https://segmentfault.com/a/1190000016412013
https://www.cnblogs.com/Dr-wei/p/11742414.html
https://xargin.com/pprof-and-flamegraph/