pprof
net/http/pprof
は、runtime/pprof
をwrapしているGoの標準ライブラリです。
これすごくよいです。
net/http
でサーバ立てておいて特定のurlを叩くと、
そのプロセスのメモリプロファイル情報を出力してくれます。
以下は/debug/pprof/heap?debug=1
の例です。
(heapの他に、goroutine, threadcreate, block等々あります)
pprof_sample.go
package main
import (
"fmt"
"net/http"
_ "net/http/pprof"
)
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "hello, world")
}
$ curl http://localhost:8080/debug/pprof/heap?debug=1
heap profile: 0: 0 [0: 0] @ heap/1048576
# runtime.MemStats
# Alloc = 584992
# TotalAlloc = 584992
# Sys = 2822144
# Lookups = 5
# Mallocs = 4958
# Frees = 98
# HeapAlloc = 584992
# HeapSys = 1769472
# HeapIdle = 876544
# HeapInuse = 892928
# HeapReleased = 0
# HeapObjects = 4860
# Stack = 327680 / 327680
# MSpan = 13600 / 16384
# MCache = 4800 / 16384
# BuckHashSys = 2598
# NextGC = 4194304
# PauseNs = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
# NumGC = 0
# DebugGC = false
さらにgo tool pprof
をかませることで人間が読みやすい形で出力してくれます。
上記のサンプルコードだとemptyが返ってきてしまうのですが、
標準入力待ちになったらtext
と打てば出力されます。
$ go tool pprof http://localhost:8080/debug/pprof/heap?debug=1
(pprof) text
これを使ってメモリリークの原因ぽいで!ってところをどんどん潰していきたいですね。