通過
net/http/pprof
工具來進行分析內存
pprof簡介
pprof
是用於可視化和分析性能分析數據的工具; 以profile.proto
讀取分析樣本的集合,並生成報告以可視化並幫助分析數據(支持文本和圖形報告)。
支持模式
- Report generation:報告生成
- Interactive terminal use:交互式終端使用
- Web interface:Web 界面
用途
- CPU Profiling:CPU 分析,按照一定的頻率採集所監聽的應用程序 CPU(含寄存器)的使用情況,可確定應用程序在主動消耗 CPU 週期時花費時間的位置
- Memory Profiling:內存分析,在應用程序進行堆分配時記錄堆棧跟蹤,用於監視當前和歷史內存使用情況,以及檢查內存泄漏
- Block Profiling:阻塞分析,記錄 goroutine 阻塞等待同步(包括定時器通道)的位置
Mutex Profiling:互斥鎖分析,報告互斥鎖的競爭情況;
使用示例
引入pprof
net/http/pprof
對 runtime/pprof
進行了封裝,並在http端口上暴露出來,入口爲 IP:PORT/debug/pprof/
;
若應用爲web服務器,只需引入包即可_ "net/http/pprof"
,會自動註冊路由到/debug/pprof/
;
若爲服務時程,可開啓一個goroutine開啓端口並監聽;
package main
import (
"github.com/astaxie/beego"
_ "github.com/beeWeb/routers"
"net/http"
_ "net/http/pprof"
)
func main() {
go func() {
http.ListenAndServe("0.0.0.0:8090", nil)
}()
beego.Run()
}
數據分析
訪問 http://127.0.0.1:8090/debug/pprof/
即可實時查看性能數據;
常用的採集分析命令:
go tool pprof http://localhost:8080/debug/pprof/profile?seconds=30 默認採集需要30秒
go tool pprof http://localhost:8080/debug/pprof/heap
-inuse_space:分析應用程序的常駐內存佔用情況
-alloc_objects:分析應用程序的內存臨時分配情況
go tool pprof http://localhost:8080/debug/pprof/block
go tool pprof http://localhost:8080/debug/pprof/mutex
命令執行後,在本地會保留一份分析報告,如pprof.alloc_objects.alloc_space.inuse_objects.inuse_space.001.pb.gz
,可以通過go tool pprof
來進行分析;
通過web可視化的方式可以分析數據:
go tool pprof -http=:8000 http://localhost:8080/debug/pprof/heap 查看內存使用
go tool pprof -http=:8000 http://localhost:8080/debug/pprof/profile 查看cpu佔用
go tool pprof -http=:8000 pprof.alloc_objects.alloc_space.inuse_objects.inuse_space.001.pb.gz 對本地生成文件的解析查看
注意,需要提前安裝
Graphviz
用於畫圖:
下載地址:https://graphviz.gitlab.io/download/
windows:https://graphviz.gitlab.io/_pages/Download/windows/graphviz-2.38.zip
解壓後,添加環境變量 Path下添加 %graphviz%\bin;
測試:命令提示符下 dot -V # 打印版本信息
若是Linux,yum install graphviz
# 默認安裝版本爲爲2.30 依賴項較多;
訪問 http://localhost:8000/ui
, 即可看到詳細的分析報告及各種圖示;
eg:
GC
windows
在cmd命令行下:
1.設置跟蹤GC的臨時環境變量
set GOGCTRACE=1
set GODEBUG=gctrace=1
2.將gc寫入日誌中
xxx.exe 2> gc.log
Linux
GODEBUG=gctrace=1 ./xxx
GODEBUG=gctrace=1 ./xxx 2> gc.log
參數說明
…