(pprof) help Commands: callgrind Outputs a graph in callgrind format comments Output all profile comments disasm Output assembly listings annotated with samples dot Outputs a graph in DOT format eog Visualize graph through eog evince Visualize graph through evince gif Outputs a graph image in GIF format gv Visualize graph through gv ......
go run main.go 2022/10/2610:33:08 profile: cpu profiling enabled, /var/folders/dd/11ddhj_s2dbdnj8mx91b97800000gn/T/profile3671108945/cpu.pprof 2022/10/2610:33:08 profile: cpu profiling disabled, /var/folders/dd/11ddhj_s2dbdnj8mx91b97800000gn/T/profile3671108945/cpu.pprof
CPU profile 文件已经在 tmp 目录生成,得到 profile 文件后,就可以像之前一样,用 go tool pprof 命令,在浏览器或命令行进行分析了。
只需要在 go test 添加 -cpuprofile 参数即可生成 BenchmarkFib 对应的 CPU profile 文件:
1 2 3 4 5 6 7 8
go test -bench="Fib$" -cpuprofile=cpu.pprof . goos: darwin goarch: amd64 pkg: Go/pprof/benchmark cpu: Intel(R) Core(TM) i5-7267U CPU @ 3.10GHz BenchmarkFib-42654732255 ns/op PASS ok Go/pprof/benchmark 1.827s
用例执行完毕后,当前目录多出了一个 cpu.pprof 文件,接下来就可以使用 go tool pprof 命令进行分析了。
1 2
go tool pprof -http=:9999 cpu.pprof Serving web UI on http://localhost:9999
也可以使用 -text 选项可以直接将结果以文本形式打印出来。
1 2 3 4 5 6 7 8 9 10
> go tool pprof -text cpu.pprof Type: cpu Time: Oct 26, 2022 at 10:53am (CST) Duration: 1.75s, Total samples = 540ms (30.80%) Showing nodes accounting for540ms, 100% of 540ms total flat flat% sum% cum cum% 540ms 100% 100% 540ms 100% Go/pprof/benchmark.fib 00% 100% 540ms 100% Go/pprof/benchmark.BenchmarkFib 00% 100% 540ms 100% testing.(*B).launch 00% 100% 540ms 100% testing.(*B).runN
pprof 支持多种输出格式(图片、文本、Web等),直接在命令行中运行 go tool pprof 即可看到所有支持的选项:
> go tool pprof Details: Output formats (select at most one): -callgrind Outputs a graph in callgrind format -comments Output all profile comments -disasm Output assembly listings annotated with samples -dot Outputs a graph in DOT format -eog Visualize graph through eog -evince Visualize graph through evince -gif Outputs a graph image in GIF format -gv Visualize graph through gv -kcachegrind Visualize report in KCachegrind -list Output annotated source for functions matching regexp -pdf Outputs a graph in PDF format -peek Output callers/callees of functions matching regexp -png Outputs a graph image in PNG format -proto Outputs the profile in compressed protobuf format -ps Outputs a graph in PS format -raw Outputs a text representation of the raw profile -svg Outputs a graph in SVG format -tags Outputs all tags in the profile -text Outputs top entries in text form -top Outputs top entries in text form -topproto Outputs top entries in compressed protobuf format -traces Outputs all profile samples in text form -tree Outputs a text rendering of call graph -web Visualize graph through web browser -weblist Display annotated source in a web browser