golang裏面自己自帶內存分析,cpu分析,堆分配信息,線程使用狀況,goroutine使用狀況.這些分析包含在runtime/pprof這個包下面,本文參考的文獻:Go性能監控/分析工具:go tool pprofgolang
先看測試代碼:web
go func() { fcup, err := os.Create("pprofcpu.log") if err != nil { fmt.Println("can't create file") return } fmem, err := os.Create("pprofmem.log") if err != nil { fmt.Println("can't create file") return } fblock, err := os.Create("pprofblock.log") if err != nil { fmt.Println("can't create file") return } froutinue, err := os.Create("pprofroutinue.log") if err != nil { fmt.Println("can't create file") return } fthread, err := os.Create("pprofthread.log") if err != nil { fmt.Println("can't create file") return } fheap, err := os.Create("pprofheap.log") if err != nil { fmt.Println("can't create file") return } for { pprof.StartCPUProfile(fcup) runtime.MemProfileRate = 512 * 1024 runtime.SetBlockProfileRate(1) time.Sleep(time.Second * 60) pprof.StopCPUProfile() pprof.WriteHeapProfile(fmem) pprof.Lookup("block").WriteTo(fblock, 2) pprof.Lookup("goroutine").WriteTo(froutinue, 2) pprof.Lookup("threadcreate").WriteTo(fthread, 2) pprof.Lookup("heap").WriteTo(fheap, 2) } }()
這個是關於分析工具部分的一段實現代碼,主要是將cpu信息,heap信息,goroutinue信息,線程信息,塊信息都保存到文件裏面.這些接口使用"runtime/pprof"的就夠了.在保持文件時,使用方法:WriteTo有兩個參數,第一個參數是保存文件的句柄,第二個參數是保持信息的基本,可設置的值分別爲0,1,2:瀏覽器
爲 0 時,僅僅輸出 pprof(程序)須要的十六進制地址函數
爲 1 時,輸出時增長函數名和行號,這樣無需工具也能夠閱讀此 profile工具
爲 2 時,而且當輸出 goroutine profile 時,輸出的 goroutine 棧的格式爲未 recovered panic 時的格式性能
這樣直接使用看起來不是很方便,go還提供了 web的形式,使用會更方便一些. 首先是須要載入包:_ "net/http/pprof"
須要注意的是必須以這樣的形式import, 由於這個包其實在帶中沒有用到,可是在運行的時候會用到,因此若是前面不帶"_"的導入,會編譯錯誤. 而後就是須要添加監聽的端口:測試
pprofMux := http.DefaultServeMux go func() { http.ListenAndServe("localhost:8081", pprofMux) }()
若是你的項目自己就是go 的web項目,那麼就是要添加兩個監聽的端口,有一個是獨立運行專門用來顯示分析數據的.當程序運行以後在瀏覽器裏面輸入以下: http://localhost:8081/debug/pprof
線程
就能夠看到想要的頁面了:debug
/debug/pprof/ Types of profiles available: Count Profile 78 allocs 0 block 0 cmdline 1043 goroutine 78 heap 0 mutex 0 profile 17 threadcreate 0 trace full goroutine stack dump Profile Descriptions: allocs: A sampling of all past memory allocations block: Stack traces that led to blocking on synchronization primitives cmdline: The command line invocation of the current program goroutine: Stack traces of all current goroutines heap: A sampling of memory allocations of live objects. You can specify the gc GET parameter to run GC before taking the heap sample. mutex: Stack traces of holders of contended mutexes profile: CPU profile. You can specify the duration in the seconds GET parameter. After you get the profile file, use the go tool pprof command to investigate the profile. threadcreate: Stack traces that led to the creation of new OS threads trace: A trace of execution of the current program. You can specify the duration in the seconds GET parameter. After you get the trace file, use the go tool trace command to investigate the trace.