pprof能夠用來調試go程序,在go中有兩個庫能夠使用,1. net/http/pprof 2. runtime/pprofhtml
# cat main1.go package main import ( _ "fmt" "net/http" _ "net/http/pprof" "time" ) func hello() { for { time.Sleep(1 * time.Microsecond) //fmt.Printf("hello\n") } } func main() { go func() { http.ListenAndServe("localhost:6060", nil) }() hello() }
http://localhost:6060/debug/pprof/
# go tool pprof http://localhost:6060/debug/pprof/heap $ go tool pprof -base pprof.demo2.alloc_objects.alloc_space.inuse_objects.inuse_space.001.pb.gz pprof.demo2.alloc_objects.alloc_space.inuse_objects.inuse_space.002.pb.gz
# go tool pprof http://localhost:6060/debug/pprof/profile # go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
# cat main2.go package main import ( _ "fmt" "os" "runtime/pprof" "time" ) func hello() { i := 0 for { time.Sleep(1 * time.Microsecond) i += 1 if i > 100000 { break } } } func main() { cpuProfile, _ := os.Create("cpu_profile") pprof.StartCPUProfile(cpuProfile) defer pprof.StopCPUProfile() hello() }
得到 cpu_profile 文件;node
# go tool pprof cpu_profile Type: cpu Time: Aug 2, 2019 at 7:46pm (CST) Duration: 1.11s, Total samples = 1.17s (105.58%) Entering interactive mode (type "help" for commands, "o" for options) (pprof) top --cum Showing nodes accounting for 430ms, 36.75% of 1170ms total Showing top 10 nodes out of 32 flat flat% sum% cum cum% 0 0% 0% 760ms 64.96% runtime.semasleep 0 0% 0% 450ms 38.46% runtime.notetsleep_internal 0 0% 0% 440ms 37.61% runtime.findrunnable 0 0% 0% 440ms 37.61% runtime.mcall 0 0% 0% 440ms 37.61% runtime.park_m 0 0% 0% 440ms 37.61% runtime.schedule 0 0% 0% 430ms 36.75% runtime.notesleep 430ms 36.75% 36.75% 430ms 36.75% runtime.pthread_cond_wait 0 0% 36.75% 430ms 36.75% runtime.stopm 0 0% 36.75% 400ms 34.19% runtime.notetsleepg (pprof)
go-torch 在 Go 1.11 以前是做爲非官方的可視化工具存在的, 它能夠爲監控數據生成一個相似下面這樣的圖形界面, 紅紅火火的, 於是得名. 從 Go 1.11 開始, 火焰圖被集成進入 Go 官方的 pprof 庫.golang
go-torch is deprecated, use pprof insteadweb
As of Go 1.11, flamegraph visualizations are available in go tool pprof directly!工具
執行:測試
go tool pprof -http=":8081" main2.go cpu_profile
go test -bench . -cpuprofile cpu.prof
// ... memProfile, _ := os.Create("mem_profile") pprof.WriteHeapProfile(memProfile)