go pprof 使用

go pprof

使用

一共有三種html

web 程序

若是自己是web 程序, 就是能夠在瀏覽器中直接訪問,能夠是系統或者http 接口api等golang

這種自己就能夠直接訪問的到,因此只須要在main 方法import中添加web

_ "net/http/pprof"

在瀏覽器中使用http://localhost:port/debug/pprof/直接看到當前web服務的狀態api

服務進程

若是是一個其餘的進程,好比是一個服務的一部分,這個時候可能並無直接用http 訪問的入口瀏覽器

這個時候就能夠使用這種方式函數

  • import 中添加3個包
import (
	 _ "net/http/pprof"
	"net/http"
	"log"
)
  • 而後在main方法中添加一個進程
go func() {
    log.Println(http.ListenAndServe("localhost:6060", nil)) 
}()

應用程序

這個時候並非web 程序, 因此前面的方式都不行了性能

須要用到 runtime/pprof.net

  • 添加
import (
	"runtime/pprof"
	"flag"
	"os"
	"log"
)
  • cpu 分析文檔
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")

func main() {
    flag.Parse()
    if *cpuprofile != "" {
        f, err := os.Create(*cpuprofile)
        if err != nil {
            log.Fatal(err)
        }
        pprof.StartCPUProfile(f)
        defer pprof.StopCPUProfile()
    }
    
    //... 其餘

}

運行程序,生成profile文件debug

這裏詳細解釋一下top命令的輸出格式,例如:code

14 2.1% 17.2% 58 8.7% std::_Rb_tree::find

各字段的含義依次是:

  1. 採樣點落在該函數中的次數

  2. 採樣點落在該函數中的百分比

  3. 上一項的累積百分比

  4. 採樣點落在該函數,以及被它調用的函數中的總次數

  5. 採樣點落在該函數,以及被它調用的函數中的總次數百分比

  6. 函數名

參考:

Go的pprof使用

Package pprof

go tool pprof

Go程序性能分析pprof

Profiling Go Programs

golang pprof記錄

PS: 以爲不錯的請點個贊吧!! (ง •̀_•́)ง

相關文章
相關標籤/搜索