介绍
Pprof是golang程序一个性能分析的工具,可以查看堆栈、cpu信息等
pprof有2个包
:net/http/pprof以及runtime/pprof
- 二者的关系
net/http/pprof包只是使用runtime/pprof包来进行封装了一下,并在http端口上暴露出来。
web 服务器
假如你的go呈现是用http包启动的web服务器,当你想要查看web服务器的状态时,选择【net/http/pprof】,使用方法如下:
import (
"net/http"
_ "net/http/pprof"
)
查看结果:通过访问http://domain:port/debug/pprof 查看当前web服务的状态。
服务进程
如果你go程序是一个服务进程,同样可以选择【net/http/pprof】包,然后开启另外一个goroutine来开启端口监听。
//远程获取pprof数据
go func() {
log.Println(http.ListenAndServe("localhost:8080", nil))
}()
应用程序
如果你的go程序只是一个应用程序,比如计算fabonacci数列,那么你就不能使用net/http/pprof包了,你就需要使用到runtime/pprof。具体做法就是用到pprof.StartCPUProfile和pprof.StopCPUProfile。比如下面的例子:
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()
}
【net/http/pprof】
package main
import (
"flag"
"log"
"net/http"
_ "net/http/pprof"
"sync"
"time"
)
func Counter(wg *sync.WaitGroup) {
time.Sleep(time.Second)
var counter int
for i := 0; i < 1000000; i++ {
time.Sleep(time.Millisecond * 200)
counter++
}
wg.Done()
}
func main() {
flag.Parse()
//远程获取pprof数据
go func() {
log.Println(http.ListenAndServe("localhost:8080", nil))
}()
var wg sync.WaitGroup
wg.Add(10)
for i := 0; i < 10; i++ {
go Counter(&wg)
}
wg.Wait()
// sleep 10mins, 在程序退出之前可以查看性能参数.
time.Sleep(60 * time.Second)
}
编译运行
:go run test.go
1、通过网页查看overview:http://localhost:8080/debug/pprof/
2、通过命令行查看
查看堆栈信息
:go tool pprof http://localhost:8080/debug/pprof/heap
进入到pprof:
top10命令 查看了堆栈空间最大的10个函数调用
web命令 则生成了很详细的图
查看cpu性能信息
:go tool pprof http://localhost:8080/debug/pprof/profile
进入到pprof:
web命令 则生成了很详细的图