1. 介紹
對於生產環境中運行的進程,可以用 Go 內置的性能分析工具 pprof 窺測進程的當前狀況。
Profiling Go Programs 很好地演示了用 pprof 找到性能瓶頸的過程,這里只演示簡單用法。
2. 啟用實時的pprof
2.1 啟用實時的 pprof
非常簡單,只需要引入 "net/http/pprof",然后啟動 http server 就可以了:
import (
"fmt"
"log"
"net/http"
_ "net/http/pprof"
"time"
)
func Write(num int, c chan int) {
for {
c <- num
}
}
func main() {
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
c := make(chan int)
go Write(10, c)
go Write(20, c)
for {
select {
case v := <-c:
fmt.Printf("receive %d\n", v)
time.Sleep(2 * time.Second)
}
}
}
直接用瀏覽器打開 http://127.0.0.1:6060/debug/pprof/ 查看:

其中 debug/pprof/profile 是 cpu 采樣文件,訪問時觸發,用 seonds 參數控制采集持續時間:
# 默認是 30 秒
http://localhost:6060/debug/pprof/profile?seconds=30
2.2 對於非常駐環境
對於非常駐運行的 Go 語言程序,可以在程序添加代碼,經 pprof 信息寫入文件中:
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
func main() {
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
...
3. 如何使用pprof
如何使用 pprof 才是重點,除了 profile 和 trace ,其它 url 可以直接在瀏覽器中查看,
profile 和 trace 是兩個采樣文件要分別用 pprof 和 trace 工具查看。
對於離線文件:
$ go tool pprof havlak1 havlak1.prof
Welcome to pprof! For help, type 'help'.
(pprof)
對於在線地址,以 cpu 采樣為例(為了采集到數據把上面程序中的 sleep 時間調整為 0):
$ go tool pprof http://localhost:6060/debug/pprof/profile # 30-second CPU profile

web 命令繪制采樣圖並用瀏覽器打開 ,如果遇到下面錯誤,安裝 graphviz:
(pprof) web
failed to execute dot. Is Graphviz installed? Error: exec: "dot": executable file not found in $PATH
MACOS上:
brew install graphviz

3. trace查看

