我是靠谱客的博主 开放咖啡豆,这篇文章主要介绍Golang pprof 工具使用,现在分享给大家,希望可以做个参考。

Golang pprof分析工具使用

1. 概述

gopprof工具可以用来监测进程的运行数据,用于监控程序的性能,对内存使用和CPU使用的情况统信息进行分析。

官方提供了两个包:runtime/pprofnet/http/pprof,前者用于普通代码的性能分析,后者用于web服务器的性能分析

2. runtime/pprof的使用

该包提供了一系列用于调试信息的方法,可以很方便的对堆栈进行调试

  • StartCPUProfile:开始监控cpu。
  • StopCPUProfile:停止监控cpu,使用StartCPUProfile后一定要调用该函数停止监控。
  • WriteHeapProfile:把堆中的内存分配信息写入分析文件中

测试代码

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main import ( "flag" "runtime/pprof" "log" "runtime" "math/rand" "os" "time" ) var cpuprofile = flag.String("cpuprofile", "", "write cpu profile `file`") var memprofile = flag.String("memprofile", "", "write memory profile to `file`") const ( col = 10000 row = 10000 ) func main() { flag.Parse() if *cpuprofile != "" { f, err := os.Create(*cpuprofile) if err != nil { log.Fatal("could not create CPU profile: ", err) } if err := pprof.StartCPUProfile(f); err != nil { //监控cpu log.Fatal("could not start CPU profile: ", err) } defer pprof.StopCPUProfile() } // 主逻辑区,进行一些简单的代码运算 x := [row][col]int{} s := rand.New(rand.NewSource(time.Now().UnixNano())) for i := 0; i < row; i++{ for j := 0; j < col; j++ { x[i][j] = s.Intn(100000) } } for i := 0; i < row; i++{ tmp := 0 for j := 0; j < col; j++ { tmp += x[i][j] } } if *memprofile != "" { f, err := os.Create(*memprofile) if err != nil { log.Fatal("could not create memory profile: ", err) } runtime.GC() // GC,获取最新的数据信息 if err := pprof.WriteHeapProfile(f); err != nil { // 写入内存信息 log.Fatal("could not write memory profile: ", err) } f.Close() } }
复制代码
1
2
3
go build ./pprof -cpuprofile cpu.prof -memprofile mem.prof // 会产生cpu分析文件和内存分析文件

然后本地运行go tool pprof cpu.prof就可以进入命令行,使用性能分析工具查看数据

  • top:命令格式:top [n],查看排名前n个数据,默认为10
  • tree:命令格式:tree [n],以树状图形式显示,默认显示10个
  • web:以web形式查看,在web服务的时候经常被用到,需要安装gv工具(macos brew install graphviz)

最后

以上就是开放咖啡豆最近收集整理的关于Golang pprof 工具使用的全部内容,更多相关Golang内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(91)

评论列表共有 0 条评论

立即
投稿
返回
顶部