这是我参与「第三届青训营 -后端场」笔记创作活动的的第1篇笔记
在编写代码时, 开发者难免写出一些低性能的代码, 而开发者在大部分情况下只能人肉debug, 而go提供了一个工具为开发者定位代码的资源消耗: pprof
它可以在运行时采集数据, 支持可视化, 可以进行一些简单的性能分析
在第三节课中使用了wolfogre/go-pprof-practice: go pprof practice. (github.com), 我也是跟着亦步亦趋的学习, 错误理解之处, 还请见谅
根据源码中的注释
// To use pprof, link this package into your program:
// import _ "net/http/pprof"
//
// If your application is not already running an http server, you
// need to start one. Add "net/http" and "log" to your imports and
// the following code to your main function:
//
// go func() {
// log.Println(http.ListenAndServe("localhost:6060", nil))
// }()
需要先导入包
在import时在包名前加"_"表示仅导入init函数
import (
"log"
"net/http"
_ "net/http/pprof"
)
再进行监听
我无法理解的是pprof如何监听这个端口的, 我试了换端口也可以
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
自带的web多少有些简陋, 好在我们并不一定要在这里查看数据
以下命令需要在程序正在运行时才能使用, 因为pprof包是开了个服务器提供数据, 这个命令从服务器取得信息进行分析 我一个人错误半天不知道为什么的教训
可以在终端中使用 go tool pprof 命令, 将采样到的信息写入文件并解析
比如go tool pprof "http://localhost:7070/debug/pprof/profile?seconds=10", 他代表采样10秒的数据,
top命令可以查看以占用CPU降序的表格
web命令可以将其可视化并在浏览器打开, 可以看见资源的调用链, 比控制台更加直观(其实是生成了一个文件?)
但是这似乎还不够简单明了, 难道我每次都要输入指令吗? 这实在不符合Windows人士的习惯!
这时老师讲了一个命令参数 -http=:8080, 但是老师没有细讲, 我报着探索的精神在控制台中看了一下他的help
-http Provide web interface at host:port.
Host is optional and 'localhost' by default.
Port is optional and a randomly available port by default.
// 在网页中提供一个界面, 默认host是'localhost', 默认端口是一个随机可用的端口
这次就可以直接用鼠标点点点来看数据了
后面老师讲的是不同资源的分析, 老师也说了是不同后缀, 我就不重复水字数了, 可以在注释中直观的看出有哪些资源是可以分析的, 它们具体有哪些属性看是什么资源
// Then use the pprof tool to look at the heap profile:
//
// go tool pprof http://localhost:6060/debug/pprof/heap
//
// Or to look at a 30-second CPU profile:
//
// go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
//
// Or to look at the goroutine blocking profile, after calling
// runtime.SetBlockProfileRate in your program:
//
// go tool pprof http://localhost:6060/debug/pprof/block
//
// Or to look at the holders of contended mutexes, after calling
// runtime.SetMutexProfileFraction in your program:
//
// go tool pprof http://localhost:6060/debug/pprof/mutex
//
// The package also exports a handler that serves execution trace data
// for the "go tool trace" command. To collect a 5-second execution trace:
//
// curl -o trace.out http://localhost:6060/debug/pprof/trace?seconds=5
// go tool trace trace.out