go内置的性能分析工具 - pprof
发布于 2022-10-13 00:10:44阅读 865
获取数据
控制台程序 - 使用runtime/pprof库
如下,一个基于 cobra 的程序
package main
import (
"cobra-demo/cmd"
"fmt"
"os"
"runtime/pprof"
)
func main() {
//start
cpuProfile, err := os.Create("./pprof/cpu_profile")
if err != nil {
fmt.Printf("创建文件失败:%s", err.Error())
return
}
defer cpuProfile.Close()
memProfile, err := os.Create("./pprof/mem_profile")
if err != nil {
fmt.Printf("创建文件失败:%s", err.Error())
return
}
defer memProfile.Close()
//采集CPU信息
pprof.StartCPUProfile(cpuProfile)
defer pprof.StopCPUProfile()
//采集内存信息
pprof.WriteHeapProfile(memProfile)
//end
cmd.Execute()
}
执行上面的程序会得到两个数据文件./pprof/cpu_profile
和./pprof/mem_profile
Web应用 - 使用net/http/pprof库
这里介绍两种:原生net/http框架和Gin框架
原生net/http框架
package main
import (
"fmt"
"net/http"
_ "net/http/pprof"
)
func HelloWorld(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hello world")
}
func main() {
http.HandleFunc("/", HelloWorld)
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Println(err)
}
}
Gin框架
package main
import (
"enterprise-api/app/routes"
"github.com/gin-contrib/pprof"
)
func main() {
//注册路由
router := routes.InitRouter()
pprof.Register(router) //就这一句
router.Run(":8080")
}
如上,无论你是用的原生net/http框架
,还是用的Gin框架
,现在都可以访问 http://localhost:8080/debug/pprof/
http://localhost:8080/debug/pprof/allocs
http://localhost:8080/debug/pprof/block
http://localhost:8080/debug/pprof/cmdline
http://localhost:8080/debug/pprof/heap
http://localhost:8080/debug/pprof/mutex
http://localhost:8080/debug/pprof/profile
http://localhost:8080/debug/pprof/threadcreate
http://localhost:8080/debug/pprof/trace
我们选一个
cuiwei@weideMacBook-Pro enterprise-api % go tool pprof http://localhost:8080/debug/pprof/allocs
Fetching profile over HTTP from http://localhost:8080/debug/pprof/allocs
Saved profile in /Users/cuiwei/pprof/pprof.alloc_objects.alloc_space.inuse_objects.inuse_space.002.pb.gz
Type: alloc_space
Time: Oct 12, 2022 at 11:45pm (CST)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof)
#这里可以进行一些交互,比如执行 top
如上我们得到了新的数据文件~/pprof/pprof.alloc_objects.alloc_space.inuse_objects.inuse_space.002.pb.gz
使用可视化界面
必须安装graphviz
#macOS
brew install graphviz
选择一个上面得到的数据文件,比如:pprof.alloc_objects.alloc_space.inuse_objects.inuse_space.002.pb.gz
cuiwei@weideMacBook-Pro enterprise-api % go tool pprof -http=localhost:8081 ~/pprof/pprof.alloc_objects.alloc_space.inuse_objects.inuse_space.002.pb.gz
Serving web UI on http://localhost:8081