分享
  1. 首页
  2. 文章

golang profile用法

上海大坤哥 · · 6714 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

概要

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.按照上文介绍的方法进入profile(go tool pprof)
2.查看profile

进入profile以后可以用 help 指令查看都有哪些指令可以使用,根据说明使用就可以了,常用命令 topN, list, 等,也可以使用web命令绘制出浏览器可查看的图形化分析


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:上海大坤哥

查看原文:golang profile用法

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
6714 次点击
暂无回复
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏