在Debian上進行Golang代碼性能分析,可按以下步驟操作:
安裝工具
golang-pprof:sudo apt-get install golang-pprof。graphviz用于可視化分析:sudo apt install graphviz。生成性能數據
net/http/pprof并啟動HTTP服務,或通過-cpuprofile參數生成文件:import _ "net/http/pprof"
func main() {
go func() { log.Println(http.ListenAndServe("localhost:6060", nil)) }()
// 程序邏輯
}
或運行程序時添加-cpuprofile cpu.prof生成文件。-memprofile mem.prof生成內存分析文件。分析性能數據
go tool pprof查看結果,常用命令:
top:查看CPU占用最高的函數。list <函數名>:查看函數內具體耗時代碼。web或-http=:8080:生成可視化圖表(需安裝graphviz)。pprof -http=:8080 cpu.prof在瀏覽器中查看交互式報告。優化建議
trace工具分析協程調度和GC行為。參考來源: