寫一段代碼測試
首先寫一個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
觀看結果

然後用指令進入:go tool pprof http://localhost:9997/debug/pprof/profile
互動:top 10
但是很不直覺對不對
是以我們安裝Graphviz 在mac下
brew install graphviz
之後再這個(pprof)裡面輸入web
會生産一個svg檔案
用右鍵快速打開我們就會看到
直覺圖解
分析
該server在main.doSomeThingOne函數上花費了81.45秒中的74.01秒。如果我們可以優化它使其運作更快,這将是向前邁出的一大步。
是以讓我們看看代碼,看看到底該函數計算的功能是什麼。
func doSomeThingOne(times int) {
for i := 0; i < times; i++ {
for j := 0; j < times; j++ {
}
}
}
這樣,便知道了性能瓶頸和待優化的點了。