golang利用pprof與go-torch如何做性能分析
前言
軟件開發(fā)過程中,項目上線并不是終點。上線后,還要對程序的取樣分析運行情況,并重構現(xiàn)有的功能,讓程序執(zhí)行更高效更穩(wěn)寫。 golang的工具包內(nèi)自帶pprof功能,使找出程序中占內(nèi)存和CPU較多的部分功能方便了不少。加上uber的火焰圖,可視化顯示,讓我們在分析程序時更簡單明了。
pprof有兩個包用來分析程序一個是net/http/pprof另一個是runtime/pprof,net/http/pprof只是對runtime/pprof包進行封裝并用http暴露出來,如下圖源碼所示:

使用net/http/pprof分析web服務
pprof分析web項目,非常的簡單只需要導入包即可。
_ "net/http/pprof"
編寫一個小的web服務器
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服務監(jiān)聽9909端口
web服務器有兩個http方法
test: 根據(jù)當前的秒數(shù)做斐波那契計算
data: 做一個5000的斐波那契計算并返回一個隨機的字符串
運行程序,通過訪問 http://192.168.3.34:9909/debug/pprof/可以查看web版的profiles相關信息

這幾個路徑表示的是
/debug/pprof/profile:訪問這個鏈接會自動進行 CPU profiling,持續(xù) 30s,并生成一個文件供下載
/debug/pprof/block:Goroutine阻塞事件的記錄。默認每發(fā)生一次阻塞事件時取樣一次。
/debug/pprof/goroutines:活躍Goroutine的信息的記錄。僅在獲取時取樣一次。
/debug/pprof/heap: 堆內(nèi)存分配情況的記錄。默認每分配512K字節(jié)時取樣一次。
/debug/pprof/mutex: 查看爭用互斥鎖的持有者。
/debug/pprof/threadcreate: 系統(tǒng)線程創(chuàng)建情況的記錄。 僅在獲取時取樣一次。
除了這些golang為我提供了更多方便的方法,用于分析,下面我們來用命令去訪問詳細的信息
我們用wrk來訪問我們的兩個方法,這樣我們的服務會處在高速運行狀態(tài),取樣的結果會更準確
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
在默認情況下,Go語言的運行時系統(tǒng)會以100 Hz的的頻率對CPU使用情況進行取樣。也就是說每秒取樣100次,即每10毫秒會取樣一次。為什么使用這個頻率呢?因為100 Hz既足夠產(chǎn)生有用的數(shù)據(jù),又不至于讓系統(tǒng)產(chǎn)生停頓。并且100這個數(shù)上也很容易做換算,比如把總取樣計數(shù)換算為每秒的取樣數(shù)。實際上,這里所說的對CPU使用情況的取樣就是對當前的Goroutine的堆棧上的程序計數(shù)器的取樣。
默認的取樣時間是30s 你可以通過-seconds 命令來指定取樣時間 。取樣完成后會進入命令行狀態(tài):

可以輸入help查看相關的命令.這里說幾個常用的命令
top命令,輸入top命令默認是返加前10的占用cpu的方法。當然人可以在命令后面加數(shù)字指定top數(shù)

list命令根據(jù)你的正則輸出相關的方法.直接跟可選項o 會輸出所有的方法。也可以指定方法名

如: 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
默認情況下取樣時只取當前內(nèi)存使用情況,可以加可選命令alloc_objects,將從程序開始時的內(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了
安裝很簡單
go get github.com/uber/go-torch cd $GOPATH/src/github.com/uber/go-torch git clone https://github.com/brendangregg/FlameGraph.git
然后運行FlameGraph下的 拷貝flamegraph.pl 到 /usr/local/bin
火焰圖分析CPU
使用命令
go-torch -u http://192.168.3.34:9909 --seconds 60 -f cpu.svg
會在當前目錄下生成cpu.svg文件,使用瀏覽器打開

更直觀的看到應用程序的問題。handlerData方法占用的cpu時間過長。然后就是去代碼里分析并優(yōu)化了。
火焰圖分析內(nèi)存
使用命令
go-torch http://192.168.3.34:9909/debug/pprof/heap --colors mem -f mem.svg
會在當前目錄下生成cpu.svg文件,使用瀏覽器打開

使用runtime/pprof分析項目
如果你的項目不是web服務,比如是rpc服務等,就要使用runtime/pprof。他提供了很多方法,有時間可以看一下源碼

我寫了一個簡單的工具類。用于調(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開放了幾個方法
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{})
思想是一樣的,會在當前文件夾內(nèi)導出profile文件。然后用火焰圖去分析,就不能指定域名了,要指定文件
go-torch httpdemo cpu.prof go-torch httpdemo mem.prof
總結
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關文章
Go語言同步等待組sync.WaitGroup結構體對象方法詳解
這篇文章主要為大家介紹了Go語言同步等待組sync.WaitGroup結構體對象方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08

