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)