zoukankan      html  css  js  c++  java
  • go程序性能优化

    性能优化总结:

    1 尽量避免频繁创建对象,即减少&{},new,make的使用
    2 数组可当切片用,当需要使用切片时,可考虑能使用数组来减少切片的创建
    3 当某类临时对象被多个协频繁程使用时,可用sync.pool做缓存
    4 当某类临时对象被少量协程频繁使用时,可预先创建对象数组来减少零碎对象数量
    5 单通道多协程的场景,可尝试多通道均分多协程实现(通道内部使用锁互斥,减少单条通道的协程数量可提高并发效率)
    6 当协程数量达到万级,应控制协程数量(协程过多,对gc影响特大 go1.4)
    7 由于调度影响,协程可预先创建的尽量预先创建,避免需要时创建,特别是响应延迟要求较低的逻辑

    性能优化方法:

    =======================CPU性能分析方法=========================

    方式一:

    对象:web程序, 在程序中引入runtime/pprof包,并添加如下代码:

        filename := "cpu_profile"           // 最好是在放在主函数中 test.pprof CPU分析文件

        f, err := os.Create(filename)

        if err != nil {

            fmt.Println(err)

            return

        }   

        pprof.StartCPUProfile(f)

        defer pprof.StopCPUProfile()

        defer f.Close()

    使用:终端执行 go tool pprof program_name cpu_profile

    方式二:

    对象:web程序,引入net/http/pprofweb的路由处理为默认处理,若非默认路由,则为其添加如下类似路由处理:

    func init() {

        http.Handle("/debug/pprof/", http.HandlerFunc(Index))

        http.Handle("/debug/pprof/cmdline", http.HandlerFunc(Cmdline))

        http.Handle("/debug/pprof/profile", http.HandlerFunc(Profile))

        http.Handle("/debug/pprof/symbol", http.HandlerFunc(Symbol))

    }

    ps:此段代码为net/http/pprof内代码,为自定义路由处理添加时将函数转换成pprof包的调用即可,如:Index  ==> pprof.Index

    使用:浏览器访问上述路径即可,也可用 go tool pprof program_name http:xxx:xx/debug/pprof/profile进入命令行交互模式使用

    方式三:

    对象:应用程序或Test案例(可执行结束的), 进入工作目录使用如下命令:

      Go test -cpuprofile filename net/http    // filename 为自定义文件名,会生成此文件和http.test文件

    使用: go tool pprof http.test filename

    ================================GC性能分析方法===========================

    设置环境变量:export GODEBUG=gctrace=1      // 具体数据含义百度~~

  • 相关阅读:
    友链
    Vue打包后处理跨域
    es6 Promise
    express get和post数据
    Nodejs登陆注册应用
    bootstrap按钮
    vue-router
    vue--transition多个元素运动
    $ git push -u origin masterremote时出现错误: error: GH007: Your push would publish a private email address.
    vue.js监听
  • 原文地址:https://www.cnblogs.com/--xiaoyao--/p/5033545.html
Copyright © 2011-2022 走看看