golang内置了pprof功能,非常方便和强大,分别有“runtime/pporf”和“net/http/pprof”包来支持。我们这里用http-server来演示。
第一步:引入net/http/pprof包
package main
import (
"fmt"
"log"
"net/http"
_ "net/http/pprof"
)
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "URL.Path=%q\n", r.URL.Path)
}
第二步:执行采样
- 采样CPU:go tool pprof http://localhost:8000/debug/pprof/profile?seconds=100
- 采样堆内存:go tool pprof http://localhost:8000/debug/pprof/heap
- 采样阻塞:go tool pprof http://localhost:8000/debug/pprof/block
- 采样Mutex:go tool pprof http://localhost:8000/debug/pprof/mutex
- 采样Trace:curl -o trace.out http://localhost:8000/debug/pprof/trace?seconds=5 go tool trace trace.out
采样结束后,会生成文件,如CPU采样生成:pprof.samples.cpu.001.pb.gz文件。可以通过命令行分析,也可以通过graphviz进行分析。
第三步:下载graphviz进行分析
mac电脑下载:brew install graphviz 然后执行命令:go tool pprof -http=:8081 pprof.samples.cpu.001.pb.gz 然后通过http://localhost:8081/ui/进行分析。
参考
https://blog.csdn.net/raoxiaoya/article/details/118493465
https://pkg.go.dev/net/http/pprof@go1.20.5
https://pkg.go.dev/runtime/pprof@go1.20.5