性能优化|青训营课程笔记

63 阅读1分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 12 天

性能分析工具 pprof

性能分析的5个方面:

1.CPU:程序对CPU的使用情况
2.内存:程序对内存的使用情况
3.I/O:I/O使用情况
4.Goroutine:协程使用情况,包括协程的泄露检查
5.deadlock:死锁检测,数据竞争分析

image.png

pprof实践项目

git clone https://github.com/wolfogre/go-pprof-practice

package main

import (
   "log"
   "net/http"
   _ "net/http/pprof"
   "os"
   "runtime"
   "time"

   "github.com/wolfogre/go-pprof-practice/animal"
)

func main() {
   log.SetFlags(log.Lshortfile | log.LstdFlags)
   log.SetOutput(os.Stdout)

   runtime.GOMAXPROCS(1)
   runtime.SetMutexProfileFraction(1)
   runtime.SetBlockProfileRate(1)

   go func() {
      if err := http.ListenAndServe(":6060", nil); err != nil {
         log.Fatal(err)
      }
      os.Exit(0)
   }()

   for {
      for _, v := range animal.AllAnimals {
         v.Live()
      }
      time.Sleep(time.Second)
   }
}
    

打开地址http://localhost:6060/debug/pprof/

image.png

解读:

18 allocs //过去是对18个对象做过内存分配
3 block   //3个阻塞
cmdline   //执行了什么命令行
goroutine //协程数
heap      //目前正在活动的对象内存分配情况,堆的内存分配情况
mutex     //锁争用情况的采样信息 
profile   //下载一个文件,对CPU采样,url加?seconds-60数据采用时间
threadcreate //告诉我们哪些位置会创建一个线程
trace     //运行过程的跟踪

打开任何一项的url后去掉后面的?debug-1会下载数据

go tool pprof http://localhost:6060/debug/pprof/allocs

go tool pprof http://localhost:6060/debug/pprof/allocs?seconds=60

会进入到一个命令交互的终端

常用指令top//默认取前10条占用资源最多的

字段解读:

flat:函数自身运行资源消耗
flat%:自身运行资源消耗百分比
Sum%:资源消耗总和所占百分比
Cum:当前函数加上它所有的调用栈运行总消耗
Cum%:百分比

list 正则表达式 //执行list,使用正则匹配,找到相关代码长耗处

web //会在浏览器生成一个svg文件

image.png