golang 入门
The Go ecosystem provides a very easy way to profile your applications.
Go生态系统提供了一种非常简单的方法来分析您的应用程序。
I’ll explain profiling using a package by Dave Cheney which makes programs very easy to debug, by adding a one-liner to our main()
.
我将说明使用Dave Cheney的软件包进行概要分析,该软件包通过在我们的main()
添加单行代码,使程序非常易于调试。
All you need to get started is follow these X easy steps.
您只需要开始执行这些X简单步骤即可。
CPU分析 (CPU Profiling)
步骤#1:下载github.com/pkg/profile
(Step #1: download github.com/pkg/profile
)
Can’t be simpler than running
比运行简单
go get github.com/pkg/profile
and you’re done.
到此为止。
步骤2:将配置文件添加到命令的main()
函数中 (Step #2: add profiling into the main()
function of your command)
package main
import (
//...
"github.com/pkg/profile"
)
func main() {
// CPU profiling by default
defer profile.Start().Stop()
//...
}
步骤#3:建立并执行程式 (Step #3: build and run your program)
This will generate a *.pprof
file in a temp folder, and tell you where it’s located (will be needed later)
这将在临时文件夹中生成一个*.pprof
文件,并告诉您文件的位置(稍后需要)
2017/08/03 14:26:28 profile: cpu profiling enabled, /var/...../cpu.pprof
步骤#4:如果尚未安装graphviz
,请安装它 (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.
这用于在pdf上生成图形。 在Mac上,这是一个简单的brew install graphviz
。 有关其他平台,请参阅https://www.graphviz.org 。
步骤#5:运行go tool pprof
(Step #5: run go tool pprof
)
Pass your binary location, and the location of the cpu.pprof
file as returned when running your program.
传递您的二进制位置,以及运行程序时返回的cpu.pprof
文件的位置。
You can generate the analysis in various formats. The PDF one is pretty amazing:
您可以生成各种格式的分析。 PDF令人惊叹:
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
:
您还可以生成其他类型的可视化效果,例如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:
内存配置与CPU配置基本相同,但是我们没有使用profile.Start()
的默认配置,而是传递了profile.MemProfile
标志:
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()
//...
}
and when running the program, it will generate a mem.pprof
file instead of cpu.pprof
.
并且在运行程序时,它将生成一个mem.pprof
文件而不是cpu.pprof
。
了解有关剖析Go应用的更多信息 (Read more about profiling Go apps)
This is just a start. Read more at:
这只是一个开始。 阅读更多信息:
Lower level: https://golang.org/pkg/runtime/pprof/
More options for advanced usage of
github.com/pkg/profile
http://godoc.org/github.com/pkg/profile进一步使用
github.com/pkg/profile
更多选项http://godoc.org/github.com/pkg/profile
golang 入门