跳到主要内容

性能优化

一 性能优化

1.1 性能优化手段

性能优化的入手点:

  • CPU性能优化
  • 内存性能优化
  • 使用火焰图进行优化
  • 性能优化实例剖析
  • Go中锁竞争维度的优化

常见性能优化手段:

  • 尽可能减少HTTP请求,比如合并css,使用精灵图
  • 使用CDN系统,实现就近访问
  • 启用gzip压缩,降低网页传输大小
  • 优化后端api服务性能(查找哪些哪些地方占用了过多资源)

当pprof开启后,每隔一段时间(10ms)收集当前堆栈信息,获取各个函数占用的cpu以及内存资源,当pprof完成之后,通过对这些数据进行分析,性能一个性能分析报告。

1.2 生成测试数据

package main

import (
"flag"
"fmt"
"os"
"runtime/pprof"
"time"
)

func logicCode() {
var c chan int
for {
select {
case v := <- c:
fmt.Printf("read from chan, v: %v\n", v)
default:

}
}
}

func main() {

var isCpuPprof bool
flag.BoolVar(&isCpuPprof, "cpu", off, "turn cpu pprof on")
flag.Parse()

if isCpuPprof {
file, err := os.Create("C:/temp/cpu.pprof")
if err != nil {
fmt.Printf("create cpu pprof failed, err:%v \n", err)
return
}
pprof.StartCPUProfile(file)
defer pprof.StopCPUProfile()
}

for i := 0; i < 8; i++ {
go logicCode()
}

time.Sleep(30 * time.Second)

}

1.3 分析数据

go tool pprof .\cpu_pprof_exam.exe .\cpu.pprof

上述命令会进入命令行模式:

top5    # 查看前五的占用函数

1.4 go test

每次都手动导入pprof比较麻烦,可以直接使用go test测试时进行pprof。

步骤:

  • 1 先编译压力测试程序,如go test -c 生成可执行程序**_test
  • 2 分析cpu性能: ./**.test-test.bench=**-test.cpuprofile=./cpu.pprof
  • 3 分析内存:./**.test-test.bench=**.test.memeprofile=./mem.pprof

1.5 火焰图性能分析图表

项目地址:https://github.com/uber/go-torch