项目结构

├── go.mod
├── go.sum
├── main.go

go.mod

module github.com/rongfengliang/gopsutillearning
go 1.13
require (
 github.com/shirou/gopsutil v2.19.11+incompatible
 github.com/stretchr/testify v1.4.0 // indirect
 golang.org/x/sys v0.0.0-20191224085550-c709ea063b76 // indirect
)
 

代码

package main
import (
 "fmt"
 "log"
 "net/http"
 _ "net/http/pprof"
 "github.com/shirou/gopsutil/mem"
)
func printinfo() {
 for {
  // fetch virtual mem info
  mem, err := mem.VirtualMemory()
  if err != nil {
   fmt.Println("some wrong", err)
  } else {
   fmt.Println((mem.String()))
  }
 }
}
func main() {
 go printinfo()
 log.Println(http.ListenAndServe("0.0.0.0:6060", nil))
}

pprof 使用

  • 启动
go run main.go
  • 基本命令
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
  • 效果

查看cpu 火焰图

  • 生成profile
    地址http://localhost:6060/debug/pprof/profile
  • 查看命令:
pprof -http 0.0.0.0:8080 profile
  • UI效果
  • 火焰图

makefile 构建

为了方便,使用make 构建跨平台的可执行文件

  • Makefile
build: clean compile
clean: 
 rm -rf pprof-demo-*
compile:
 echo "Compiling for every OS and Platform"
 GOOS=darwin GOARCH=amd64 go build -o pprof-demo-mac main.go
 GOOS=linux GOARCH=amd64 go build -o pprof-demo-linux main.go
 GOOS=windows GOARCH=amd64 go build -o pprof-demo-windows.exe main.go
 
  • 使用
make build

说明

golang 的pprof 功能强大,是把应用性能分析的利器,注意需要安装graphviz,结合自己的系统选择安装对应的版本

参考资料

https://golang.org/pkg/net/http/pprof/
https://github.com/google/pprof
https://github.com/rongfengliang/gopsutillearning
https://github.com/shirou/gopsutil

12-16 13:52