什么是pprof
pprof是Go的性能分析工具,在程序运行过程中,可以记录程序的运行信息,可以是CPU使用情况、内存使用情况、goroutine运行情况等,当需要性能调优或者定位Bug时候,这些记录的信息是相当重要。
代码实现
package main
import (
"fmt"
"net/http"
_ "net/http/pprof" // 引入pprof,调用init方法
)
func main() {
// 生产环境应仅在本地监听pprof
go func() {
ip := "127.0.0.1:9527"
if err := http.ListenAndServe(ip, nil); err != nil {
fmt.Println("开启pprof失败", ip, err)
}
}()
// 业务代码运行中
http.ListenAndServe("0.0.0.0:8081", nil)
}
使用方式
1.浏览器方式
地址:http://127.0.0.1:9527/debug/pp