Go CPU和內存分析入門

Go生態系統提供了一種非常簡單的方法來分析您的應用程序。

我將說明使用Dave Cheney的軟件包進行性能分析,該軟件包通過在我們的程序中添加單行代碼使程序非常易於調試main()

您只需要開始執行以下X個簡單步驟即可。

CPU分析

步驟1:下載github.com/pkg/profile

比運行簡單

go get github.com/pkg/profile

到此為止。

步驟2:將配置文件添加到main()您命令的功能

package main

import ( //… github.com/pkg/profile )

func main() { // CPU profiling by default defer profile.Start().Stop()

<span style="color:#75715e">//...

}

步驟#3:生成並運行程序

這將產生一個*.pprof文件放在臨時文件夾中,然後告訴您它的位置(稍後需要)

2017/08/03 14:26:28 profile: cpu profiling enabled, /var/...../cpu.pprof

Step #4: install graphviz if you don’t have it installed yet

This is used to generate the graph on a pdf. On a Mac, it’s a simple brew install graphviz. Refer to https://www.graphviz.org for other platforms.

Step #5: run go tool pprof

Pass your binary location, and the location of the cpu.pprof file as returned when running your program.

You can generate the analysis in various formats. The PDF one is pretty amazing:

go tool pprof --pdf ~/go/bin/yourbinary /var/path/to/cpu.pprof > file.pdf

You can generate other kind of visualizations as well, e.g. txt:

go tool pprof --txt ~/go/bin/yourbinary /var/path/to/cpu.pprof > file.txt

Memory profiling

Memory profiling is essentially the same as CPU profiling, but instead of using the default configuration for profile.Start(), we pass a profile.MemProfile flag:

defer profile.Start(profile.MemProfile).Stop()

thus the code becomes

package main

import ( //… github.com/pkg/profile )

func main() { // Memory profiling defer profile.Start(profile.MemProfile).Stop()

<span style="color:#75715e">//...

}

and when running the program, it will generate a mem.pprof file instead of cpu.pprof.

Read more about profiling Go apps

This is just a start. Read more at:


More go tutorials: