使用pprof调试go程序

使用pprof调试go程序

pprof可以用来调试go程序,在go中有两个库可以使用,1. net/http/pprof 2. runtime/pprof

方法1 - net/http/pprof

测试代码

  • 启动http的方式
# cat main1.go
package main

import (
	_ "fmt"
	"net/http"
	_ "net/http/pprof"
	"time"
)

func hello() {
	for {
		time.Sleep(1 * time.Microsecond)
		//fmt.Printf("hello\n")
	}
}

func main() {
	go func() {
		http.ListenAndServe("localhost:6060", nil)
	}()
	hello()
}

查看web

http://localhost:6060/debug/pprof/

分析MEM

# go tool pprof http://localhost:6060/debug/pprof/heap

$ go tool pprof -base pprof.demo2.alloc_objects.alloc_space.inuse_objects.inuse_space.001.pb.gz pprof.demo2.alloc_objects.alloc_space.inuse_objects.inuse_space.002.pb.gz

分析CPU

# go tool pprof http://localhost:6060/debug/pprof/profile
# go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30

方法2 - runtime/pprof

测试代码

  • 注意,必须要执行完才可以
# cat main2.go
package main

import (
	_ "fmt"
	"os"
	"runtime/pprof"
	"time"
)

func hello() {
	i := 0
	for {
		time.Sleep(1 * time.Microsecond)
		i += 1

		if i > 100000 {
			break
		}
	}
}

func main() {
	cpuProfile, _ := os.Create("cpu_profile")
	pprof.StartCPUProfile(cpuProfile)
	defer pprof.StopCPUProfile()
	hello()
}

获得 cpu_profile 文件;

分析CPU:

命令行读取cpu_profile 文件

# go tool pprof cpu_profile
Type: cpu
Time: Aug 2, 2019 at 7:46pm (CST)
Duration: 1.11s, Total samples = 1.17s (105.58%)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) top --cum
Showing nodes accounting for 430ms, 36.75% of 1170ms total
Showing top 10 nodes out of 32
      flat  flat%   sum%        cum   cum%
         0     0%     0%      760ms 64.96%  runtime.semasleep
         0     0%     0%      450ms 38.46%  runtime.notetsleep_internal
         0     0%     0%      440ms 37.61%  runtime.findrunnable
         0     0%     0%      440ms 37.61%  runtime.mcall
         0     0%     0%      440ms 37.61%  runtime.park_m
         0     0%     0%      440ms 37.61%  runtime.schedule
         0     0%     0%      430ms 36.75%  runtime.notesleep
     430ms 36.75% 36.75%      430ms 36.75%  runtime.pthread_cond_wait
         0     0% 36.75%      430ms 36.75%  runtime.stopm
         0     0% 36.75%      400ms 34.19%  runtime.notetsleepg
(pprof)

Flame Graph读取cpu_profile 文件

go-torch 在 Go 1.11 之前是作为非官方的可视化工具存在的, 它可以为监控数据生成一个类似下面这样的图形界面, 红红火火的, 因而得名. 从 Go 1.11 开始, 火焰图被集成进入 Go 官方的 pprof 库.

go-torch is deprecated, use pprof instead

As of Go 1.11, flamegraph visualizations are available in go tool pprof directly!

执行:

go tool pprof -http=":8081" main2.go cpu_profile

测试

go test -bench . -cpuprofile cpu.prof

采集MEM:

// ...
memProfile, _ := os.Create("mem_profile")
pprof.WriteHeapProfile(memProfile)

Docs

posted @ 2019-08-02 13:30  苏小北1024  阅读(1768)  评论(0编辑  收藏  举报