golang pprof 查看哪些goroutine 在增加

90 阅读1分钟

启动 CPU 和 Goroutine Profiling: 首先,你需要在你的程序中启用 CPU 和 Goroutine Profiling。你可以使用标准库中的 net/http/pprof 包来实现这一点。

go package main

import ( "net/http" _ "net/http/pprof" "log" )

func main() { go func() { log.Println(http.ListenAndServe("localhost:6060", nil)) }()

// 你的程序逻辑
// ...

select {} // 保持程序运行

} 这样,你可以在 http://localhost:6060/debug/pprof/ 上访问 pprof 页面。

捕获第一个 Goroutine Profile

curl -o goroutine.out1 http://localhost:8088/debug/pprof/goroutine curl -o heap.out1 http://localhost:8088/debug/pprof/heap

运行你的程序逻辑,等待一段时间后,捕获第二个 Goroutine Profile

curl -o goroutine.out2 http://localhost:8088/debug/pprof/goroutine curl -o heap.out2 http://localhost:8088/debug/pprof/heap

对比

go tool pprof -http=:8080 -base goroutine.out1 goroutine.out2

go tool pprof -http=:8080 -base heap.out1 heap.out2

生成svg: go tool pprof -svg -base goroutine.out1 goroutine.out2 > goroutine.svg

go tool pprof -svg -base heap.out1 heap.out2 > heap.svg