go pprof 简单使用

测试demo

package main

import (
    "flag"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    _ "net/http/pprof"
    "sync"
    "time"
)

func counter() {
    list := []int{1}
    c := 1
    for i := 0; i < 10000000; i++ {
        httpGet()
        c = i + 1 + 2 + 3 + 4 - 5
        list = append(list, c)
    }
    fmt.Println(c)
    fmt.Println(list[0])
}

func work(wg *sync.WaitGroup) {
    for {
        counter()
        time.Sleep(1 * time.Second)
    }
    wg.Done()
}

func httpGet() int {
    queue := []string{"start..."}
    resp, err := http.Get("http://www.163.com")
    if err != nil {
        // handle error
    }

    //defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }
    queue = append(queue, string(body))
    return len(queue)
}

func main() {
    flag.Parse()

    //这里实现了远程获取pprof数据的接口
    go func() {
        log.Println(http.ListenAndServe("localhost:7777", nil))
    }()

    var wg sync.WaitGroup
    wg.Add(10)
    for i := 0; i < 100; i++ {
        go work(&wg)
    }

    wg.Wait()
    time.Sleep(3 * time.Second)
}

运行后会启动一个debug端口,打开对应端口的url,可以看到当前统计。
使用命令行进行交互,获取当前状态:

go tool  pprof --text http://localhost:7777/debug/pprof/heap

Fetching profile from http://localhost:7777/debug/pprof/heap
Saved profile in /Users/wanhongfei/pprof/pprof.localhost:7777.alloc_objects.alloc_space.inuse_objects.inuse_space.004.pb.gz
34193.53kB of 34193.53kB total (  100%)
Dropped 64 nodes (cum <= 170.97kB)
      flat  flat%   sum%        cum   cum%
29515.08kB 86.32% 86.32% 29515.08kB 86.32%  bytes.makeSlice
 3140.36kB  9.18% 95.50%  3140.36kB  9.18%  compress/flate.NewReader
     514kB  1.50% 97.01%  3654.36kB 10.69%  compress/gzip.(*Reader).Reset
  512.06kB  1.50% 98.50%   512.06kB  1.50%  compress/flate.(*huffmanDecoder).init
  512.03kB  1.50%   100%   512.03kB  1.50%  runtime.systemstack
         0     0%   100% 33681.50kB 98.50%  bytes.(*Buffer).ReadFrom
         0     0%   100%   512.06kB  1.50%  compress/flate.(*decompressor).Read
         0     0%   100%   512.06kB  1.50%  compress/flate.(*decompressor).nextBlock

猜你喜欢

转载自blog.csdn.net/qq_17612199/article/details/80290953