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: 以为不错的请点个赞吧!! (ง •̀_•́)ง

相关文章
相关标签/搜索