我是靠谱客的博主 开放咖啡豆,最近开发中收集的这篇文章主要介绍Golang pprof 工具使用,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Golang pprof分析工具使用

1. 概述

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

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

2. runtime/pprof的使用

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

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

测试代码

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()
}
}
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 pprof 工具使用所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部