zl程序教程

您现在的位置是:首页 >  其他

当前栏目

golang测试

2023-03-14 22:31:18 时间

转自
http://studygolang.com/articles/1155
http://www.tuicool.com/articles/RnMJrm

参考:
http://blog.golang.org/profiling-go-programs
http://google-perftools.googlecode.com/svn/trunk/doc/cpuprofile.html

  1. 代码
    要在Go语言中开启profiling,可以参考以下代码:

import (

"runtime/pprof"     // 引用pprof package
"os"

)
func main() {

f, _ := os.Create("profile_file")
pprof.StartCPUProfile(f)  // 开始cpu profile,结果写到文件f中
defer pprof.StopCPUProfile()  // 结束profile

}

  1. 运行
    运行程序,生成profile文件
  2. 分析
    在命令行上执行:

go tool pprof [binary] [profile]
进入pprof环境后,可以用help命令查看帮助信息
最常用的命令如top10,可以看最耗时的function
这里详细解释一下top命令的输出格式,例如:
14 2.1% 17.2% 58 8.7% std::_Rb_tree::find
各字段的含义依次是:

  1. 采样点落在该函数中的次数
  2. 采样点落在该函数中的百分比
  3. 上一项的累积百分比
  4. 采样点落在该函数,以及被它调用的函数中的总次数
  5. 采样点落在该函数,以及被它调用的函数中的总次数百分比
  6. 函数名