Go性能分析利器pprof(一)
当我们的程序遇到性能瓶颈或者内存泄漏等问题时,除了使用perf、strace、pmap等命令定位问题之外,Go本身也提供了一个分析的工具pprof(本文介绍runtime.pprof)
pprof的使用
想使用pprof需要做三件事
1. 代码中嵌入pprof逻辑
使用pprof查看内存使用的例子
package main
import (
"log"
"os"
"runtime/pprof"
)
var g []int
func main() {
//写入信息的文件
f, err := os.Create("mem.prof")
if err != nil {
log.Fatal("could not create memory profile: ", err)
}
fibonacci(30)
if err := pprof.WriteHeapProfile(f); err != nil {
log.Fatal("could not write memory profile: ", err)
}
defer f.Close()
}
func fibonacci(n int) (res int) {
if n <= 1 {
res = 1
} else {
res = fibonacci(n-1) + fibonacci(n-2)
}
g = append(g, res)
return res
}
使用pprof查看CPU使用的例子
package main
import (
"fmt"
"log"
"os"
"runtime/pprof"
)
func main() {
f, err := os.Create("cpu.prof")
if err != nil {
log.Fatal("could not create CPU profile: ", err)
}
if err := pprof.StartCPUProfile(f); err != nil {
log.Fatal("could not start CPU profile: ", err)
}
defer pprof.StopCPUProfile()
for i := 0; i < 102400; i++ {
s := make([]byte, 3)
fmt.Sprint(s, "hello world\n")
}
}
2. 运行程序
使用go run运行上述的程序,此时可以看到当前目录下产生了cpu.prof/mem.prof
3.使用go tool查看分析
# 使用交互终端查看cpu使用信息
go tool pprof cpu.prof
# 使用交互终端查看内存使用信息
go tool pprof mem.prof
# 使用web页面查看cpu使用信息
go tool pprof -http=0.0.0.0:8000 cpu.prof
# 使用web页面查看内存使用信息
go tool pprof -http=0.0.0.0:8000 mem.prof
pprof交互命令
- top 查看占用最多的n个节点
- traces 各节点的调用trace信息
- tree Outputs a text rendering of call graph
文档信息
- 本文作者:KcJia
- 本文链接:https://blog.kcjia.cn/2021/07/21/go-pprof-1/
- 版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)