golang 使用pprof和go-torch做性能分析

軟件開發過程中,項目上線並不是終點。上線後,還要對程序的取樣分析運行情況,並重構現有的功能,讓程序執行更高效更穩寫。 golang的工具包內自帶pprof功能,使找出程序中佔內存和CPU較多的部分功能方便了不少。加上uber的火焰圖,可視化顯示,讓我們在分析程序時更簡單明瞭。

pprof有兩個包用來分析程序一個是net/http/pprof另一個是runtime/pprof,net/http/pprof只是對runtime/pprof包進行封裝並用http暴露出來,如下圖源碼所示:

golang 使用pprof和go-torch做性能分析

使用net/http/pprof分析web服務

pprof分析web項目,非常的簡單隻需要導入表即可。

<code>_ "net/http/pprof"/<code>

編寫一個小的web服務器

<code>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 := Count = int64(i.Second())
}
}
}/<code>

web服務監聽9909端口

web服務器有兩個http方法 test: 根據當前的秒數做斐波那契計算 data: 做一個5000的斐波那契計算並返回一個隨機的字符串

運行程序,通過訪問 http://192.168.3.34:9909/debug/pprof/可以查看web版的profiles相關信息

golang 使用pprof和go-torch做性能分析

這幾個路徑表示的是

/debug/pprof/profile:訪問這個鏈接會自動進行 CPU profiling,持續 30s,並生成一個文件供下載

/debug/pprof/block:Goroutine阻塞事件的記錄。默認每發生一次阻塞事件時取樣一次。

/debug/pprof/goroutines:活躍Goroutine的信息的記錄。僅在獲取時取樣一次。

/debug/pprof/heap: 堆內存分配情況的記錄。默認每分配512K字節時取樣一次。

/debug/pprof/mutex: 查看爭用互斥鎖的持有者。

/debug/pprof/threadcreate: 系統線程創建情況的記錄。 僅在獲取時取樣一次。

除了這些golang為我提供了更多方便的方法,用於分析,下面我們來用命令去訪問詳細的信息

我們用wrk來訪問我們的兩個方法,這樣我們的服務會處在高速運行狀態,取樣的結果會更準確

<code>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/<code>

分析CPU使用情況

使用命令分析CPU使用情況

<code>go tool pprof httpdemo http://192.168.3.34:9909/debug/pprof/profile/<code>

在默認情況下,Go語言的運行時系統會以100 Hz的的頻率對CPU使用情況進行取樣。也就是說每秒取樣100次,即每10毫秒會取樣一次。為什麼使用這個頻率呢?因為100 Hz既足夠產生有用的數據,又不至於讓系統產生停頓。並且100這個數上也很容易做換算,比如把總取樣計數換算為每秒的取樣數。實際上,這裡所說的對CPU使用情況的取樣就是對當前的Goroutine的堆棧上的程序計數器的取樣。

默認的取樣時間是30s 你可以通過-seconds 命令來指定取樣時間 。取樣完成後會進入命令行狀態:

golang 使用pprof和go-torch做性能分析

可以輸入help查看相關的命令.這裡說幾個常用的命令

top命令,輸入top命令默認是返加前10的佔用cpu的方法。當然人可以在命令後面加數字指定top數

golang 使用pprof和go-torch做性能分析

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

golang 使用pprof和go-torch做性能分析

如: handlerData方法佔cpu的74.81%

web命令:以網頁的形式展現:更直觀的顯示cpu的使用情況

golang 使用pprof和go-torch做性能分析

分析內存使用情況

和分析cpu差不多使用命令

<code>go tool pprof httpdemo http://192.168.3.34:9909/debug/pprof/heap/<code>

默認情況下取樣時只取當前內存使用情況,可以加可選命令alloc_objects,將從程序開始時的內存取樣

<code>go tool pprof -alloc_objects httpdemo http://192.168.3.34:9909/debug/pprof/heap/<code>

和cpu的命令一樣,top list web。不同的是這裡顯示的是內存使用情況而已。這裡我就不演示了。

golang 使用pprof和go-torch做性能分析


安裝go-torch

還有更方便的工具就是uber的 go-torch了

安裝很簡單

<code>go get github.com/uber/go-torch
cd $GOPATH/src/github.com/uber/go-torch
git clone https://github.com/brendangregg/FlameGraph.git/<code>

然後運行FlameGraph下的 拷貝 flamegraph.pl 到 /usr/local/bin

火焰圖分析CPU

使用命令

<code>go-torch -u http://192.168.3.34:9909  --seconds 60 -f cpu.svg/<code>

會在當前目錄下生成cpu.svg文件,使用瀏覽器打開

golang 使用pprof和go-torch做性能分析

更直觀的看到應用程序的問題。handlerData方法佔用的cpu時間過長。然後就是去代碼裡分析並優化了。

火焰圖分析內存

使用命令

<code>go-torch  http://192.168.3.34:9909/debug/pprof/heap --colors mem  -f mem.svg/<code>

會在當前目錄下生成cpu.svg文件,使用瀏覽器打開

golang 使用pprof和go-torch做性能分析

使用runtime/pprof分析項目

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

golang 使用pprof和go-torch做性能分析

我寫了一個簡單的工具類。用於調用分析

<code>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()
}/<code>

在需要分析的方法內調用這些方法就可以 比如我是用rpc開放了幾個方法

<code>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
}/<code>

調用

<code>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{})/<code>

思想是一樣的,會在當前文件夾內導出profile文件。然後用火焰圖去分析,就不能指定域名了,要指定文件

<code> go-torch  httpdemo cpu.prof 
go-torch httpdemo mem.prof/<code>


分享到:


相關文章: