使用pprof調試go程序
pprof可以用來調試go程序,在go中有兩個庫可以使用,1. net/http/pprof 2. runtime/pprof
方法1 - net/http/pprof
測試代碼
- 啟動http的方式
# 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()
}
查看web
http://localhost:6060/debug/pprof/
分析MEM
# 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
分析CPU
# go tool pprof http://localhost:6060/debug/pprof/profile
# go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
方法2 - runtime/pprof
測試代碼
- 注意,必須要執行完才可以
# 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 文件;
分析CPU:
命令行讀取cpu_profile 文件
# 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)
Flame Graph讀取cpu_profile 文件
go-torch 在 Go 1.11 之前是作為非官方的可視化工具存在的, 它可以為監控數據生成一個類似下面這樣的圖形界面, 紅紅火火的, 因而得名. 從 Go 1.11 開始, 火焰圖被集成進入 Go 官方的 pprof 庫.
go-torch is deprecated, use pprof instead
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
采集MEM:
// ...
memProfile, _ := os.Create("mem_profile")
pprof.WriteHeapProfile(memProfile)
