• golang性能分析


    golang性能分析

    go-torch 使用

    1.)安装graphviz

    apt intstall graphviz
    

    2.)安装go-torch

    go get github.com/uber/go-torch
    下载并复制flamegraph.pl到$GOPATH/bin下
    https://github.com/brendangregg/FlameGraph
    

    输出prof到文件

    通过调用runtime/pprof的API实现。go支持多种Profile,可以用go help testflag查看。
    (1.)代码中插入输出cpu、mem的代码块

    // 获取CPU信息
    func main(){
        // 创建输出文件
        f,_ := os.Create("cpu.prof")
        defer f.Close()
        // 获取系统信息
        _ := pprof.StartCPUProfile(f)
    
        defer pprof.StopCPUProfile()
    }
    
    // 获取内存信息
    func main(){
        // 创建输出文件
        f,_ := os.Create("mem.prof")
        // 获取系统信息
        _ := pprof.WriteHeapProfile(f)
        f1.Close()
    
        // 查看goroutine
        f1,_ := os.Create("goroutine.prof")
        gProf := pprof.Lookup("goroutine");
        gProf.WriteTo(f1,0)
        defer f1.Close()
    }
    

    (2.)编译运行后会自动输出对应的文件

    go build xx.go  //生成二进制文件
    ./xx  // 运行二进制文件
    
    // 使用pprof工具查看
    go tool pprof prof cpu.prof  // 查看Cpu的性能数据,输入top,可以查看前十个占用cpu的代码块,可以使用list 方法名  查看具体某个方法占用的内存,执行时间等
    
    // 或者使用go-torch查看
    go-torch cpu.prof  // top
    
    # 下载cpu profile,默认从当前开始收集30s的cpu使用情况,需要等待30s
    go tool pprof http://localhost:9527/debug/pprof/profile   # 30-second CPU profile
    go tool pprof http://localhost:9527/debug/pprof/profile?seconds=120     # wait 120s
    
    # 下载heap profile
    go tool pprof http://localhost:9527/debug/pprof/heap      # heap profile
    
    # 下载goroutine profile
    go tool pprof http://localhost:9527/debug/pprof/goroutine # goroutine profile
    
    # 下载block profile
    go tool pprof http://localhost:9527/debug/pprof/block     # goroutine blocking profile
    
    # 下载mutex profile
    go tool pprof http://localhost:9527/debug/pprof/mutex
    

    详细内容,可查看: https://golang.org/src/runtime/pprof/pprof.go

    使用HTTP的方式输出Profile

    1.)在应用程序中导入pprof包,并启动http server

    import _ "net/http/pprof"
    

    2.) 查看界面

    http://IP:Port/debug/pprof
    

    3.) 也可以通过pprof工具查看

    go tool pprof _http://IP:PORT/debug/pprof/profile?seconds=10   // top -cum |  list xxx  | exit
    
    go-torch seconds 10 http://IP:PORT/debug/pprof/profile
    

    使用go test bench测试

    go test -bench=.
    go test -bench=. -cpuprofile=cpu.prof  // top -cum  | list xx | exit
    
    【励志篇】: 古之成大事掌大学问者,不惟有超世之才,亦必有坚韧不拔之志。
  • 相关阅读:
    java数组
    java 常用类
    java 集合(一)
    mysql相关操作(一)
    记录java BigDecimal
    hxg-yw
    一个困惑我好久的问题
    关于重载和重写的一些小知识
    几个常用的HTTP状态码
    死锁产生的原因和条件简述
  • 原文地址:https://www.cnblogs.com/tomtellyou/p/14672449.html
Copyright © 2020-2023  润新知