golang利用pprof與go-torch如何做性能分析
前言
軟件開發(fā)過程中,項(xiàng)目上線并不是終點(diǎn)。上線后,還要對(duì)程序的取樣分析運(yùn)行情況,并重構(gòu)現(xiàn)有的功能,讓程序執(zhí)行更高效更穩(wěn)寫。 golang的工具包內(nèi)自帶pprof功能,使找出程序中占內(nèi)存和CPU較多的部分功能方便了不少。加上uber的火焰圖,可視化顯示,讓我們?cè)诜治龀绦驎r(shí)更簡(jiǎn)單明了。
pprof有兩個(gè)包用來分析程序一個(gè)是net/http/pprof另一個(gè)是runtime/pprof,net/http/pprof只是對(duì)runtime/pprof包進(jìn)行封裝并用http暴露出來,如下圖源碼所示:
使用net/http/pprof分析web服務(wù)
pprof分析web項(xiàng)目,非常的簡(jiǎn)單只需要導(dǎo)入包即可。
_ "net/http/pprof"
編寫一個(gè)小的web服務(wù)器
package main import ( _ "net/http/pprof" "net/http" "time" "math/rand" "fmt" ) var Count int64 = 0 func main() { go calCount() http.HandleFunc("/test", test) http.HandleFunc("/data", handlerData) err := http.ListenAndServe(":9909", nil ) if err != nil { panic(err) } } func handlerData(w http.ResponseWriter, r *http.Request) { qUrl := r.URL fmt.Println(qUrl) fibRev := Fib() var fib uint64 for i:= 0; i < 5000; i++ { fib = fibRev() fmt.Println("fib = ", fib) } str := RandomStr(RandomInt(100, 500)) str = fmt.Sprintf("Fib = %d; String = %s", fib, str) w.Write([]byte(str)) } func test(w http.ResponseWriter, r *http.Request) { fibRev := Fib() var fib uint64 index := Count arr := make([]uint64, index) var i int64 for ; i < index; i++ { fib = fibRev() arr[i] = fib fmt.Println("fib = ", fib) } time.Sleep(time.Millisecond * 500) str := fmt.Sprintf("Fib = %v", arr) w.Write([]byte(str)) } func Fib() func() uint64 { var x, y uint64 = 0, 1 return func() uint64 { x, y = y, x + y return x } } var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") func RandomStr(num int) string { seed := time.Now().UnixNano() if seed <= 0 { seed = time.Now().UnixNano() } rand.Seed(seed) b := make([]rune, num) for i := range b { b[i] = letterRunes[rand.Intn(len(letterRunes))] } return string(b) } func RandomInt(min, max int) int { rand.Seed(time.Now().UnixNano()) return rand.Intn(max - min + 1) + min } func calCount() { timeInterval := time.Tick(time.Second) for { select { case i := <- timeInterval: Count = int64(i.Second()) } } }
web服務(wù)監(jiān)聽9909端口
web服務(wù)器有兩個(gè)http方法
test: 根據(jù)當(dāng)前的秒數(shù)做斐波那契計(jì)算
data: 做一個(gè)5000的斐波那契計(jì)算并返回一個(gè)隨機(jī)的字符串
運(yùn)行程序,通過訪問 http://192.168.3.34:9909/debug/pprof/可以查看web版的profiles相關(guān)信息
這幾個(gè)路徑表示的是
/debug/pprof/profile:訪問這個(gè)鏈接會(huì)自動(dòng)進(jìn)行 CPU profiling,持續(xù) 30s,并生成一個(gè)文件供下載
/debug/pprof/block:Goroutine阻塞事件的記錄。默認(rèn)每發(fā)生一次阻塞事件時(shí)取樣一次。
/debug/pprof/goroutines:活躍Goroutine的信息的記錄。僅在獲取時(shí)取樣一次。
/debug/pprof/heap: 堆內(nèi)存分配情況的記錄。默認(rèn)每分配512K字節(jié)時(shí)取樣一次。
/debug/pprof/mutex: 查看爭(zhēng)用互斥鎖的持有者。
/debug/pprof/threadcreate: 系統(tǒng)線程創(chuàng)建情況的記錄。 僅在獲取時(shí)取樣一次。
除了這些golang為我提供了更多方便的方法,用于分析,下面我們來用命令去訪問詳細(xì)的信息
我們用wrk來訪問我們的兩個(gè)方法,這樣我們的服務(wù)會(huì)處在高速運(yùn)行狀態(tài),取樣的結(jié)果會(huì)更準(zhǔn)確
wrk -c 20 -t 5 -d 3m http://192.168.3.34:9909/data wrk -c 20 -t 5 -d 3m http://192.168.3.34:9909/test
分析CPU使用情況
使用命令分析CPU使用情況
go tool pprof httpdemo http://192.168.3.34:9909/debug/pprof/profile
在默認(rèn)情況下,Go語言的運(yùn)行時(shí)系統(tǒng)會(huì)以100 Hz的的頻率對(duì)CPU使用情況進(jìn)行取樣。也就是說每秒取樣100次,即每10毫秒會(huì)取樣一次。為什么使用這個(gè)頻率呢?因?yàn)?00 Hz既足夠產(chǎn)生有用的數(shù)據(jù),又不至于讓系統(tǒng)產(chǎn)生停頓。并且100這個(gè)數(shù)上也很容易做換算,比如把總?cè)佑?jì)數(shù)換算為每秒的取樣數(shù)。實(shí)際上,這里所說的對(duì)CPU使用情況的取樣就是對(duì)當(dāng)前的Goroutine的堆棧上的程序計(jì)數(shù)器的取樣。
默認(rèn)的取樣時(shí)間是30s 你可以通過-seconds 命令來指定取樣時(shí)間 。取樣完成后會(huì)進(jìn)入命令行狀態(tài):
可以輸入help查看相關(guān)的命令.這里說幾個(gè)常用的命令
top命令,輸入top命令默認(rèn)是返加前10的占用cpu的方法。當(dāng)然人可以在命令后面加數(shù)字指定top數(shù)
list命令根據(jù)你的正則輸出相關(guān)的方法.直接跟可選項(xiàng)o 會(huì)輸出所有的方法。也可以指定方法名
如: handlerData方法占cpu的74.81%
web命令:以網(wǎng)頁的形式展現(xiàn):更直觀的顯示cpu的使用情況
分析內(nèi)存使用情況
和分析cpu差不多使用命令
go tool pprof httpdemo http://192.168.3.34:9909/debug/pprof/heap
默認(rèn)情況下取樣時(shí)只取當(dāng)前內(nèi)存使用情況,可以加可選命令alloc_objects,將從程序開始時(shí)的內(nèi)存取樣
go tool pprof -alloc_objects httpdemo http://192.168.3.34:9909/debug/pprof/heap
和cpu的命令一樣,top list web。不同的是這里顯示的是內(nèi)存使用情況而已。這里我就不演示了。
安裝go-torch
還有更方便的工具就是uber的go-torch了
安裝很簡(jiǎn)單
go get github.com/uber/go-torch cd $GOPATH/src/github.com/uber/go-torch git clone https://github.com/brendangregg/FlameGraph.git
然后運(yùn)行FlameGraph下的 拷貝flamegraph.pl 到 /usr/local/bin
火焰圖分析CPU
使用命令
go-torch -u http://192.168.3.34:9909 --seconds 60 -f cpu.svg
會(huì)在當(dāng)前目錄下生成cpu.svg文件,使用瀏覽器打開
更直觀的看到應(yīng)用程序的問題。handlerData方法占用的cpu時(shí)間過長(zhǎng)。然后就是去代碼里分析并優(yōu)化了。
火焰圖分析內(nèi)存
使用命令
go-torch http://192.168.3.34:9909/debug/pprof/heap --colors mem -f mem.svg
會(huì)在當(dāng)前目錄下生成cpu.svg文件,使用瀏覽器打開
使用runtime/pprof分析項(xiàng)目
如果你的項(xiàng)目不是web服務(wù),比如是rpc服務(wù)等,就要使用runtime/pprof。他提供了很多方法,有時(shí)間可以看一下源碼
我寫了一個(gè)簡(jiǎn)單的工具類。用于調(diào)用分析
package profapp import ( "os" "rrnc_im/lib/zaplogger" "go.uber.org/zap" "runtime/pprof" "runtime" ) func StartCpuProf() { f, err := os.Create("cpu.prof") if err != nil { zaplogger.Error("create cpu profile file error: ", zap.Error(err)) return } if err := pprof.StartCPUProfile(f); err != nil { zaplogger.Error("can not start cpu profile, error: ", zap.Error(err)) f.Close() } } func StopCpuProf() { pprof.StopCPUProfile() } //--------Mem func ProfGc() { runtime.GC() // get up-to-date statistics } func SaveMemProf() { f, err := os.Create("mem.prof") if err != nil { zaplogger.Error("create mem profile file error: ", zap.Error(err)) return } if err := pprof.WriteHeapProfile(f); err != nil { zaplogger.Error("could not write memory profile: ", zap.Error(err)) } f.Close() } // goroutine block func SaveBlockProfile() { f, err := os.Create("block.prof") if err != nil { zaplogger.Error("create mem profile file error: ", zap.Error(err)) return } if err := pprof.Lookup("block").WriteTo(f, 0); err != nil { zaplogger.Error("could not write block profile: ", zap.Error(err)) } f.Close() }
在需要分析的方法內(nèi)調(diào)用這些方法就可以 比如我是用rpc開放了幾個(gè)方法
type TestProf struct { } func (*TestProf) StartCpuProAct(context.Context, *im_test.TestRequest, *im_test.TestRequest) error { profapp.StartCpuProf() return nil } func (*TestProf) StopCpuProfAct(context.Context, *im_test.TestRequest, *im_test.TestRequest) error { profapp.StopCpuProf() return nil } func (*TestProf) ProfGcAct(context.Context, *im_test.TestRequest, *im_test.TestRequest) error { profapp.ProfGc() return nil } func (*TestProf) SaveMemAct(context.Context, *im_test.TestRequest, *im_test.TestRequest) error { profapp.SaveMemProf() return nil } func (*TestProf) SaveBlockProfileAct(context.Context, *im_test.TestRequest, *im_test.TestRequest) error { profapp.SaveBlockProfile() return nil }
調(diào)用
profTest.StartCpuProAct(context.TODO(), &im_test.TestRequest{}) time.Sleep(time.Second * 30) profTest.StopCpuProfAct(context.TODO(), &im_test.TestRequest{}) profTest.SaveMemAct(context.TODO(), &im_test.TestRequest{}) profTest.SaveBlockProfileAct(context.TODO(), &im_test.TestRequest{})
思想是一樣的,會(huì)在當(dāng)前文件夾內(nèi)導(dǎo)出profile文件。然后用火焰圖去分析,就不能指定域名了,要指定文件
go-torch httpdemo cpu.prof go-torch httpdemo mem.prof
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
Go語言metrics應(yīng)用監(jiān)控指標(biāo)基本使用說明
這篇文章主要為大家介紹了Go語言metrics應(yīng)用監(jiān)控指標(biāo)的基本使用說明,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-02-02Go語言同步等待組sync.WaitGroup結(jié)構(gòu)體對(duì)象方法詳解
這篇文章主要為大家介紹了Go語言同步等待組sync.WaitGroup結(jié)構(gòu)體對(duì)象方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08盤點(diǎn)總結(jié)2023年Go并發(fā)庫有哪些變化
這篇文章主要為大家介紹了2023年Go并發(fā)庫的變化盤點(diǎn)總結(jié),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12