golang profile用法

概要

profile就是定时采样,收集cpu,内存等信息,进而给出性能优化指导,golang 官方提供了golang自己的性能分析工具的用法,也给出了指导,官方的介绍

环境

golang环境, graphviz

生成profile方法

golang目前提供了3中profile,分别是 cpu profile, memery profile, blocking profile, 对于如何生成这些profile有两种办法,一种是使用 net/http/pprof 包,一种是需要自己手写代码,下面分别介绍一下

1. net/http/pprof 方法

这种方法是非常非常简单的,只需要引入 net/http/pprof 包就可以了,网页上可以查看

package main

import (
    "fmt"
    "log"
    "net/http"
    _ "net/http/pprof"
)

func main() {
    go func() {
        for {
            fmt.Println("hello world")
        }
    }()
    log.Fatal(http.ListenAndServe("0.0.0.0:8080", nil))
}

http://127.0.0.1:8080/debug/pprof 查看整体信息
http://127.0.0.1:8080/debug/pprof/profile 可以将cpu profile下载下来观察分析

从terminal进入profile,进行细致分析
go tool pprof http://localhost:6060/debug/pprof/profile
go tool pprof http://localhost:6060/debug/pprof/heap
go tool pprof http://localhost:6060/debug/pprof/block

  1. 写代码的方法
func main() {
    cpuf, err := os.Create("cpu_profile")
    if err != nil {
        log.Fatal(err)
    }
    pprof.StartCPUProfile(cpuf)
    defer pprof.StopCPUProfile()

    ctx, _ := context.WithTimeout(context.Background(), time.Second*5)
    test(ctx)

    time.Sleep(time.Second * 3)
    memf, err := os.Create("mem_profile")
    if err != nil {
        log.Fatal("could not create memory profile: ", err)
    }
    if err := pprof.WriteHeapProfile(memf); err != nil {
        log.Fatal("could not write memory profile: ", err)
    }
    memf.Close()
}

func test(c context.Context) {
    i := 0
    j := 0
    go func() {
        m := map[int]int{}
        for {
            i++
            m[i] = i
        }
    }()
    go func() {
        m := map[int]int{}
        for {
            j++
            m[i] = i
        }
    }()
    select {
    case <-c.Done():
        fmt.Println("done, i", i, "j", j)
        return
    }
}

会生成两个profile,一个是cpu的,一个是内存的。进入proflie 方法

go tool pprof main profile
main 代表的是二进制文件,也就是编译出来的可执行文件
profile 就是上文中生成的profile,可以是cpu_profile, 也可以是mem_profile

对于cpu_profile 来说,代码开始的时候就可以开始统计了
mem_profile 部分代码如果写在代码开始的位置是统计不出来的,需要找到一个比较好的位置

如何分析 profile

1.示例代码如下
package main

import (
    "flag"
    "fmt"
    "log"
    "math/rand"
    "os"
    "runtime/pprof"
    "sort"
    "time"
)

var num = 100000000
var findNum = 10000000

var t = flag.String("t", "map", "use map")

func main() {
    cpuf, err := os.Create("cpu_profile")
    if err != nil {
        log.Fatal(err)
    }
    pprof.StartCPUProfile(cpuf)
    defer pprof.StopCPUProfile()

    flag.Parse()
    if *t == "map" {
        fmt.Println("map")
        findMapMax()
    } else {
        fmt.Println("slice")
        findSliceMax()
    }
}

func findMapMax() {
    m := map[int]int{}
    for i := 0; i < num; i++ {
        m[i] = i
    }

    for i := 0; i < findNum; i++ {
        toFind := rand.Int31n(int32(num))
        _ = m[int(toFind)]
    }
}

func findSliceMax() {
    m := make([]int, num)
    for i := 0; i < num; i++ {
        m[i] = i
    }

    for i := 0; i < findNum; i++ {
        toFind := rand.Int31n(int32(num))
        v := sort.SearchInts(m, int(toFind))
        fmt.Println(v)
    }
}

代码很简单,主要是为了介绍如何分析profile,达到效果即可,不要在意细节。
这段代码就是分别用 map, slice 两种数据结构, 先生成 num 个元素,在从map, slice 中 随机找到 findNum 个元素, 选用map 还是 slice 可以通过 -t 来指定,本demo采用 非 net/http/pprof 方式

2.准备工作

需要生成 profile 文件 和 二进制文件
生成二进制文件: go build main.go (执行命令后会生成 main 二进制文件)
生成 profile: ./main (不指定-t ,默认使用map数据结构,会生成 cpu_profile, 这个文件就是我们要分析的profile)

3.分析profile
  • 现在准备工作做好了,我们目前生成了 main 二进制可执行文件,cpu_profile 性能分析需要的profile, 接下来我们要正式进入profile进行分析了

  • go tool pprof main cpu_profile 执行这个命令就进入了profile 文件了,这时候我们已经可以开始分析代码了

  • 输入help,可以查看都支持哪些操作,有很多命令可以根据需要进行选择,我们只介绍4个我自己比较喜欢用的命令 web, top, peek, list
    *web—– 在profile输入 web, 会生成网页版的调用分析图(需要安装 graphviz)如下图:

    《golang profile用法》 image

    输入web命令后,会自动打开浏览器出现如下内容:

    《golang profile用法》 image

这样就可以看到每个步骤占用多少时间了,可以对性能进行大致的分析,但是很多时候可能出现的并不是我们关心的,比如这个demo中看到的都是不认识的函数(其实都是map的runtime操作)

  • top—– 在profile 中输入top,会列出来几个最耗时的操作

    《golang profile用法》 image

因为性能统计都是采样操作,所以不是每次统计出来的都一样, 最重要的是经常统计出来的都是底层操作,并不是我们关心的,而且也不是每个人都能看得懂,我们更需要一种直观的办法,很直观的能把自己写的代码耗时都看出来,下面就介绍一种我个人觉得非常好的方法。

  • peek,list 妙用
    peek 是用来查询 函数名字的(这个名字是list需要使用的名字,并不完全等于函数名)
    list 是用来将函数时间消耗列出来的
    1)list main.main

    《golang profile用法》 image

  1. peek findMapMax (因为根据1可以看出来消耗都在 findMapMax)

    《golang profile用法》 image

    3)list main.findMapMax (根据2可以看出来名字是 main.findMapMax)

    《golang profile用法》 image

妙用 peek list指令可以很直观的看出来,我们的代码问题在 m[i] = i, 这就说明了就是map的写操作耗费了38.75s, 而44行的读操作只用了2.35s, 针对这个demo,我们要优化的就是 m[i] = i ,因为这句操作已经语言级别的,我们是没有能力对他进行优化的,所以这时候如果需求只能用map,那么这个程序几乎没有优化空间了,如果需求可以使用其他的数据结构,那我们肯定会把map修改为slice,众所周知 map 每次存一个函数都要进行hash计算,而且存的多了到达一定的数量,还要重新对map进行重新分配空间的操作,所以肯定是耗时的。

总结

  1. go run main.go -t=slice 会使用slice的数据结构,同学们可以自行按照文章的方法进行分析一下,检验一下自己掌握的如何。
  2. 在profile中执行help命令,会列出所有的命令,有兴趣可以去研究
  3. memory 也是同样的分析方法,demo 中 mem_profile 生成的位置可能需要调整,我没有进行验证,降低memory 使用也会大幅提升性能。
  4. 还有一种 blocking profile 在手写方式中没有给出,有兴趣的可以自己google一下

过早的优化是万恶之源

](http://upload-images.jianshu.io/upload_images/5659111-2ccd8741843d9033?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)](https://www.jianshu.com/u/a070959706be)

上海大坤哥 已关注

2017.04.01 10:59* 字数 1485 阅读 539评论 2喜欢 8

概要

profile就是定时采样,收集cpu,内存等信息,进而给出性能优化指导,golang 官方提供了golang自己的性能分析工具的用法,也给出了指导,官方的介绍

环境

golang环境, graphviz

生成profile方法

golang目前提供了3中profile,分别是 cpu profile, memery profile, blocking profile, 对于如何生成这些profile有两种办法,一种是使用 net/http/pprof 包,一种是需要自己手写代码,下面分别介绍一下

1. net/http/pprof 方法

这种方法是非常非常简单的,只需要引入 net/http/pprof 包就可以了,网页上可以查看

package main

import (
    "fmt"
    "log"
    "net/http"
    _ "net/http/pprof"
)

func main() {
    go func() {
        for {
            fmt.Println("hello world")
        }
    }()
    log.Fatal(http.ListenAndServe("0.0.0.0:8080", nil))
}

http://127.0.0.1:8080/debug/pprof 查看整体信息
http://127.0.0.1:8080/debug/pprof/profile 可以将cpu profile下载下来观察分析

从terminal进入profile,进行细致分析
go tool pprof http://localhost:6060/debug/pprof/profile
go tool pprof http://localhost:6060/debug/pprof/heap
go tool pprof http://localhost:6060/debug/pprof/block

  1. 写代码的方法
func main() {
    cpuf, err := os.Create("cpu_profile")
    if err != nil {
        log.Fatal(err)
    }
    pprof.StartCPUProfile(cpuf)
    defer pprof.StopCPUProfile()

    ctx, _ := context.WithTimeout(context.Background(), time.Second*5)
    test(ctx)

    time.Sleep(time.Second * 3)
    memf, err := os.Create("mem_profile")
    if err != nil {
        log.Fatal("could not create memory profile: ", err)
    }
    if err := pprof.WriteHeapProfile(memf); err != nil {
        log.Fatal("could not write memory profile: ", err)
    }
    memf.Close()
}

func test(c context.Context) {
    i := 0
    j := 0
    go func() {
        m := map[int]int{}
        for {
            i++
            m[i] = i
        }
    }()
    go func() {
        m := map[int]int{}
        for {
            j++
            m[i] = i
        }
    }()
    select {
    case <-c.Done():
        fmt.Println("done, i", i, "j", j)
        return
    }
}

会生成两个profile,一个是cpu的,一个是内存的。进入proflie 方法

go tool pprof main profile
main 代表的是二进制文件,也就是编译出来的可执行文件
profile 就是上文中生成的profile,可以是cpu_profile, 也可以是mem_profile

对于cpu_profile 来说,代码开始的时候就可以开始统计了
mem_profile 部分代码如果写在代码开始的位置是统计不出来的,需要找到一个比较好的位置

如何分析 profile

1.示例代码如下
package main

import (
    "flag"
    "fmt"
    "log"
    "math/rand"
    "os"
    "runtime/pprof"
    "sort"
    "time"
)

var num = 100000000
var findNum = 10000000

var t = flag.String("t", "map", "use map")

func main() {
    cpuf, err := os.Create("cpu_profile")
    if err != nil {
        log.Fatal(err)
    }
    pprof.StartCPUProfile(cpuf)
    defer pprof.StopCPUProfile()

    flag.Parse()
    if *t == "map" {
        fmt.Println("map")
        findMapMax()
    } else {
        fmt.Println("slice")
        findSliceMax()
    }
}

func findMapMax() {
    m := map[int]int{}
    for i := 0; i < num; i++ {
        m[i] = i
    }

    for i := 0; i < findNum; i++ {
        toFind := rand.Int31n(int32(num))
        _ = m[int(toFind)]
    }
}

func findSliceMax() {
    m := make([]int, num)
    for i := 0; i < num; i++ {
        m[i] = i
    }

    for i := 0; i < findNum; i++ {
        toFind := rand.Int31n(int32(num))
        v := sort.SearchInts(m, int(toFind))
        fmt.Println(v)
    }
}

代码很简单,主要是为了介绍如何分析profile,达到效果即可,不要在意细节。
这段代码就是分别用 map, slice 两种数据结构, 先生成 num 个元素,在从map, slice 中 随机找到 findNum 个元素, 选用map 还是 slice 可以通过 -t 来指定,本demo采用 非 net/http/pprof 方式

2.准备工作

需要生成 profile 文件 和 二进制文件
生成二进制文件: go build main.go (执行命令后会生成 main 二进制文件)
生成 profile: ./main (不指定-t ,默认使用map数据结构,会生成 cpu_profile, 这个文件就是我们要分析的profile)

3.分析profile
  • 现在准备工作做好了,我们目前生成了 main 二进制可执行文件,cpu_profile 性能分析需要的profile, 接下来我们要正式进入profile进行分析了

  • go tool pprof main cpu_profile 执行这个命令就进入了profile 文件了,这时候我们已经可以开始分析代码了

  • 输入help,可以查看都支持哪些操作,有很多命令可以根据需要进行选择,我们只介绍4个我自己比较喜欢用的命令 web, top, peek, list
    *web—– 在profile输入 web, 会生成网页版的调用分析图(需要安装 graphviz)如下图:

    《golang profile用法》 image

    输入web命令后,会自动打开浏览器出现如下内容:

    《golang profile用法》 image

这样就可以看到每个步骤占用多少时间了,可以对性能进行大致的分析,但是很多时候可能出现的并不是我们关心的,比如这个demo中看到的都是不认识的函数(其实都是map的runtime操作)

  • top—– 在profile 中输入top,会列出来几个最耗时的操作

    《golang profile用法》 image

因为性能统计都是采样操作,所以不是每次统计出来的都一样, 最重要的是经常统计出来的都是底层操作,并不是我们关心的,而且也不是每个人都能看得懂,我们更需要一种直观的办法,很直观的能把自己写的代码耗时都看出来,下面就介绍一种我个人觉得非常好的方法。

  • peek,list 妙用
    peek 是用来查询 函数名字的(这个名字是list需要使用的名字,并不完全等于函数名)
    list 是用来将函数时间消耗列出来的
    1)list main.main

    《golang profile用法》 image

  1. peek findMapMax (因为根据1可以看出来消耗都在 findMapMax)

    《golang profile用法》 image

    3)list main.findMapMax (根据2可以看出来名字是 main.findMapMax)

    《golang profile用法》 image

妙用 peek list指令可以很直观的看出来,我们的代码问题在 m[i] = i, 这就说明了就是map的写操作耗费了38.75s, 而44行的读操作只用了2.35s, 针对这个demo,我们要优化的就是 m[i] = i ,因为这句操作已经语言级别的,我们是没有能力对他进行优化的,所以这时候如果需求只能用map,那么这个程序几乎没有优化空间了,如果需求可以使用其他的数据结构,那我们肯定会把map修改为slice,众所周知 map 每次存一个函数都要进行hash计算,而且存的多了到达一定的数量,还要重新对map进行重新分配空间的操作,所以肯定是耗时的。

总结

  1. go run main.go -t=slice 会使用slice的数据结构,同学们可以自行按照文章的方法进行分析一下,检验一下自己掌握的如何。
  2. 在profile中执行help命令,会列出所有的命令,有兴趣可以去研究
  3. memory 也是同样的分析方法,demo 中 mem_profile 生成的位置可能需要调整,我没有进行验证,降低memory 使用也会大幅提升性能。
  4. 还有一种 blocking profile 在手写方式中没有给出,有兴趣的可以自己google一下

过早的优化是万恶之源

    原文作者:糖果果老师
    原文地址: https://www.jianshu.com/p/79807449da2d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞