Golang Profiling - pprof 使用

Golang Profiling - pprof 使用

在编写大型应用程序,处理复杂业务与逻辑时,开发者经常面临系统内存泄漏问题。查找代码是否有效运行的一种有效方法是检查内存堆、CPU、磁盘的使用情况。

要在运行时检查Go应用程序的CPU和内存使用情况以及其他配置文件,开发者可以使用 pprof包。根据profile提供的基础功能在运行时检查以下详细信息:

  • CPU
  • Memory/Heap
  • Thread/Go routines
  • Block
  • Mutex

pprof 用法的基本顺序如下

  • 启动 profiles
  • 保存 profiles文件
  • 分析 profiles

开启Profile

导入pprof包并设置Web服务器以获取go profile。要做到这一点,只需要引入pprof包即可

import  _ "net/http/pprof"

完整代码如下

package main

import (
	"fmt"
	"log"
	"net/http"
	_ "net/http/pprof"
	"sync"
	"time"
)

func main() {
	// we need a webserver to get the pprof webserver
	go func() {
		log.Println(http.ListenAndServe("localhost:6060", nil))
	}()
	fmt.Println("hello world")
	var wg sync.WaitGroup
	wg.Add(1)
	go leakyFunction(wg)
	wg.Wait()
}

func leakyFunction(wg sync.WaitGroup) {
	defer wg.Done()
	s := make([]string, 3)
	for i := 0; i < 10000000; i++ {
		s = append(s, "magical pandas")
		if (i % 100000) == 0 {
			time.Sleep(500 * time.Millisecond)
		}
	}
}

代码开发完成之后,启动程序

保存Profile

运行Go应用程序,选择待分析的Profile信息,调用web服务获取profile相关指标。

  • 获取运行时堆栈信息
curl http://localhost:6060/debug/pprof/heap
  • 如需要获取最近运行时间内堆栈信息,使用以下命令
curl http://localhost:6060/debug/pprof/heap?seconds=n
  • 开发者可以很方便的将运行时的堆栈信息保存为指定文件,便于时候分析
curl http://localhost:6060/debug/pprof/heap --output heap.tar.gz

在这里插入图片描述

在这里插入图片描述

分析Profile

分析堆栈信息,可以使用 go tool pprof命令,格式如下

go tool pprof heap.tar.gz

进入交互shell后,输入top命令查看内存中正在使用的函数,以及每个函数的内存使用量

在这里插入图片描述

为了简化操作的复杂性(需要先存储文件,再分析),可以将这两个步骤 合并成一个指令

go tool pprof -top http://localhost:6060/debug/pprof/heap

在这里插入图片描述

  • 其他用法

Profile 可以从各种维度分析应用程序的实时运行状态,具体包含以下几类

goroutine    - stack traces of all current goroutines
heap         - a sampling of all heap allocations
threadcreate - stack traces that led to the creation of new OS threads
block        - stack traces that led to blocking on synchronization primitives
mutex        - stack traces of holders of contended mutexes
  • 获取CPU信息
curl http://localhost:6060/debug/pprof/goroutine > goroutine.tar.gz
  • 获取Thread信息
curl http://localhost:6060/debug/pprof/threadcreate > thread.tar.gz
  • 获取Profile信息
curl http://localhost:6060/debug/pprof/profile > profile.tar.gz
  • 获取trace信息
curl http://localhost:6060/debug/pprof/trace?seconds=5 > trace.tar.gz
  • 获取block信息
curl http://localhost:6060/debug/pprof/block > block.tar.gz
  • 获取mutex信息
curl http://localhost:6060/debug/pprof/mutex > mutex.tar.gz
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值