天天看点

pprof对go的性能监控

写一段代码测试

首先写一个demo:

package main

import (
	"bytes"
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	_ "net/http/pprof"
)

func main() {
	http.HandleFunc("/test", handler)
	log.Fatal(http.ListenAndServe(":9997", nil))
}

func handler(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if nil != err {
		w.Write([]byte(err.Error()))
		return
	}
	log.Println(r.Form)
	doSomeThingOne(10000)
	buff := genSomeBytes()
	b, err := ioutil.ReadAll(buff)
	if nil != err {
		w.Write([]byte(err.Error()))
		return
	}
	w.Write(b)
}

func doSomeThingOne(times int) {
	for i := 0; i < times; i++ {
		for j := 0; j < times; j++ {

		}
	}
}

func genSomeBytes() *bytes.Buffer {
	var buff bytes.Buffer
	for i := 1; i < 20000; i++ {
		buff.Write([]byte{'0' + byte(rand.Intn(10))})
	}
	return &buff
}
           

里面负责2件事:

doSomeThingOne

genSomeBytes

运行起来,执行 go run pprof_t.go

使用wrk压测

新开启一个terminal窗口,执行:./wrk -c400 -t8 -d5m http://localhost:9997/test

(上面pprof_t.go里面监听的是port :9997)

参数说明:-c400means we have 400 connections to keep open

-t8means we use 8 threads to build requests

-d5mmeans the duration of the test will last for 5 minutes

观看结果

pprof对go的性能监控

然后用命令进入:go tool pprof http://localhost:9997/debug/pprof/profile

交互:top 10

pprof对go的性能监控

但是很不直观对不对

所以我们安装Graphviz 在mac下

brew install graphviz

之后再这个(pprof)里面输入web

pprof对go的性能监控

会生产一个svg文件

用右键快速打开我们就会看到

pprof对go的性能监控

直观图解

pprof对go的性能监控

分析

该server在main.doSomeThingOne函数上花费了81.45秒中的74.01秒。如果我们可以优化它使其运行更快,这将是向前迈出的一大步。

所以让我们看看代码,看看到底该函数计算的功能是什么。

func doSomeThingOne(times int) {
  for i := 0; i < times; i++ {
    for j := 0; j < times; j++ {

    }
  }
}
           

这样,便知道了性能瓶颈和待优化的点了。