简单版
import(
"net/http"
_ "net/http/pprof"
)
go func() {
log.Info(http.ListenAndServe("localhost:6060", nil))
}()
$ go tool pprof http://10.111.101.121:6060/debug/pprof/profile
$ web
通过 Web 界面
-
查看当前总览:访问 http://127.0.0.1:6060/debug/pprof
/debug/pprof/ profiles: 0 block 5 goroutine 3 heap 0 mutex 9 threadcreate full goroutine stack dump 这个页面中有许多子页面,咱们继续深究下去,看看可以得到什么? cpu(CPU Profiling): $HOST/debug/pprof/profile,默认进行 30s 的 CPU Profiling,得到一个分析用的 profile 文件 block(Block Profiling):$HOST/debug/pprof/block,查看导致阻塞同步的堆栈跟踪 goroutine:$HOST/debug/pprof/goroutine,查看当前所有运行的 goroutines 堆栈跟踪 heap(Memory Profiling): $HOST/debug/pprof/heap,查看活动对象的内存分配情况 mutex(Mutex Profiling):$HOST/debug/pprof/mutex,查看导致互斥锁的竞争持有者的堆栈跟踪 threadcreate:$HOST/debug/pprof/threadcreate,查看创建新OS线程的堆栈跟踪
通过交互式终端使用
-
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=60
$ go tool pprof http://localhost:6060/debug/pprof/profile\?seconds\=60 Fetching profile over HTTP from http://localhost:6060/debug/pprof/profile?seconds=60 Saved profile in /Users/eddycjy/pprof/pprof.samples.cpu.007.pb.gz Type: cpu Duration: 1mins, Total samples = 26.55s (44.15%) Entering interactive mode (type "help" for commands, "o" for options) (pprof)
执行该命令后,需等待 60 秒(可调整 seconds 的值),pprof 会进行 CPU Profiling。结束后将默认进入 pprof 的交互式命令模式,可以对分析的结果进行查看或导出。具体可执行 pprof help 查看命令说明 flat:给定函数上运行耗时 flat%:同上的 CPU 运行耗时总比例 sum%:给定函数累积使用 CPU 总比例 cum:当前函数加上它之上的调用运行总耗时 cum%:同上的 CPU 运行耗时总比例 最后一列为函数名称,在大多数的情况下,我们可以通过这五列得出一个应用程序的运行情况,加以优化 ?
-
go tool pprof http://localhost:6060/debug/pprof/heap
$ go tool pprof http://localhost:6060/debug/pprof/heap Fetching profile over HTTP from http://localhost:6060/debug/pprof/heap Saved profile in /Users/eddycjy/pprof/pprof.alloc_objects.alloc_space.inuse_objects.inuse_space.008.pb.gz Type: inuse_space Entering interactive mode (type "help" for commands, "o" for options) (pprof) top Showing nodes accounting for 837.48MB, 100% of 837.48MB total flat flat% sum% cum cum% 837.48MB 100% 100% 837.48MB 100% main.main.func1 -inuse_space:分析应用程序的常驻内存占用情况 -alloc_objects:分析应用程序的内存临时分配情况
-
go tool pprof http://localhost:6060/debug/pprof/block
-
go tool pprof http://localhost:6060/debug/pprof/mutex