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


軟件開發過程中,項目上線並不是終點。上線后,還要對程序的取樣分析運行情況,並重構現有的功能,讓程序執行更高效更穩寫。 golang的工具包內自帶pprof功能,使找出程序中占內存和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 (
    "fmt"
    "math/rand"
    "net/http"
    _ "net/http/pprof"
    "time"
)
 
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服務監聽9909端口,web服務器有兩個http方法:  test: 根據當前的秒數做斐波那契計算;    data: 做一個5000的斐波那契計算並返回一個隨機的字符串 運行程序,通過訪問 http://localhost:9909/debug/pprof/ 可以查看web版的profiles相關信息

 

 

    這幾個路徑表示的是

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

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

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

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

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

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

分析CPU使用情況 

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

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

 

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

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

 

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

 

     如: handlerData方法占cpu的100%

web命令:以網頁的形式展現:更直觀的顯示cpu的使用情況【windows 下需要下載Graphviz  ,下載后需要配置環境變量path ,不認會提示錯誤】

 

  分析內存使用情況

      和分析cpu差不多使用命令 go tool pprof httpdemo http://localhost:9909/debug/pprof/heap

      默認情況下取樣時只取當前內存使用情況,可以加可選命令alloc_objects,將從程序開始時的內存取樣 go tool pprof -alloc_objects httpdemo http://localhost:9909/debug/pprof/heap

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

 安裝go-torch

    還有更方便的工具就是uber的 go-torch了   安裝很簡單

  1.  
    go get github.com /uber/go-torch
  2.  
    cd $GOPATH /src/github.com/uber/go-torch
  3.  
    git clone https://github.com/brendangregg/FlameGraph.git

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

    火焰圖分析CPU

     使用命令 go-torch -u http://localhost:9909 --seconds 60 -f cpu.svg

在windows 下會提示: [0mFailed: could not generate flame graph: fork/exec D:\GoProject\src\FlameGraph\flamegraph.pl: %1 is not a valid Win32 application. 解決辦法如下:

先下載perl https://www.activestate.com/products/perl/downloads/  或者 https://pan.baidu.com/s/107UTzX-9_vgFPTW93Ec3AA【需要確保添加了環境變量, 可以通過 perl -v  查看版本,安裝路徑中不要有空格  比如Program Files 中有空格也是有問題的 】

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

     

 

 

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

 火焰圖分析內存

    使用命令

go-torch  http://localhost:9909/debug/pprof/heap --colors mem  -f mem.svg

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

 

 參考:

https://blog.csdn.net/u014023993/article/details/98161776

https://www.jianshu.com/p/a22174de24c7?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

https://www.cnblogs.com/li-peng/p/9391543.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM