Go Engineer Comprehensive Course 020

Performance Optimization and pprof

1. Measure First, Optimize Later

"Premature optimization is the root of all evil." — Donald Knuth

Optimization Process:
1. Write correct code first
2. Use Benchmark to identify performance bottlenecks
3. Use pprof to pinpoint specific locations
4. Optimize → Measure again → Compare

2. pprof Tool

2.1 Integration in HTTP Services

import _ "net/http/pprof" // 只需导入即可

func main() {
    // 如果已有 HTTP 服务,pprof 自动注册到 DefaultServeMux
    http.ListenAndServe(":8080", nil)
}

// 如果用 gin/echo 等框架,单独启动 pprof 服务
func main() {
    go func() {
        http.ListenAndServe(":6060", nil) // pprof 单独端口
    }()
    // 启动主服务...
}

Visit http://localhost:6060/debug/pprof/ to view the overview.

2.2 Usage in Non-HTTP Programs

import "runtime/pprof"

func main() {
    // CPU Profile
    cpuFile, _ := os.Create("cpu.prof")
    defer cpuFile.Close()
    pprof.StartCPUProfile(cpuFile)
    defer pprof.StopCPUProfile()

    // 业务代码...
    doWork()

    // Heap Profile
    heapFile, _ := os.Create("heap.prof")
    defer heapFile.Close()
    pprof.WriteHeapProfile(heapFile)
}

2.3 Profile Types

Profile Description HTTP Path
CPU CPU usage hotspots /debug/pprof/profile?seconds=30
Heap Heap memory allocation /debug/pprof/heap
Allocs Cumulative memory allocation /debug/pprof/allocs
Goroutine Goroutine stack traces /debug/pprof/goroutine
Block Blocking waits /debug/pprof/block
Mutex Mutex contention /debug/pprof/mutex
Threadcreate Thread creation /debug/pprof/threadcreate
# 采集 30 秒 CPU profile
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30

# 采集堆内存
go tool pprof http://localhost:6060/debug/pprof/heap

# 查看 goroutine(检测泄漏)
go tool pprof http://localhost:6060/debug/pprof/goroutine

# 需要先开启 block/mutex profiling
runtime.SetBlockProfileRate(1)
runtime.SetMutexProfileFraction(1)

3. pprof Visualization

3.1 Command-line Interactive Mode

go tool pprof cpu.prof
# 或远程采集
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30

# 进入交互模式后:
(pprof) top 10          # 前 10 个热点函数
(pprof) top -cum        # 按累计时间排序
(pprof) list funcName   # 查看函数源码级别的耗时
(pprof) web             # 浏览器打开 SVG 图(需要 graphviz)
(pprof) png             # 输出 PNG 图
(pprof) peek funcName   # 查看调用者和被调用者

Interpreting top output:

      flat  flat%   sum%        cum   cum%
     3.20s 40.00% 40.00%      3.20s 40.00%  runtime.memclrNoHeapPointers
     1.60s 20.00% 60.00%      4.80s 60.00%  main.processData
     0.80s 10.00% 70.00%      0.80s 10.00%  runtime.memmove
  • flat: Time spent by the function itself (excluding calls to other functions)
  • cum (cumulative): Total time spent by the function (including all called sub-functions)
  • sum%: Cumulative percentage

3.2 Flame Graph

# Go 1.11+ 内置 Web UI(推荐)
go tool pprof -http=:8081 cpu.prof

# 浏览器自动打开,可以看到:
# - Top: 函数排名
# - Graph: 调用图
# - Flame Graph: 火焰图
# - Source: 源码级别
# - Peek: 上下游关系

How to read a Flame Graph:
- X-axis: Sampling proportion (wider = more time spent)
- Y-axis: Call stack depth (higher = deeper call stack)
- Color: No special meaning, only for differentiation
- Focus: Widest blocks at the top = most time-consuming leaf functions

3.3 go tool trace

Finer granularity than pprof, showing goroutine scheduling, GC events, etc.

import "runtime/trace"

func main() {
    f, _ := os.Create("trace.out")
    defer f.Close()
    trace.Start(f)
    defer trace.Stop()

    // 业务代码...
}
go tool trace trace.out
# 浏览器打开,可以看到:
# - Goroutine analysis: goroutine 数量和执行时间线
# - Network/Sync blocking: 网络和锁阻塞
# - Syscall blocking: 系统调用阻塞
# - Scheduler latency: 调度延迟
# - GC events: GC 时间线

4. Benchmark-Driven Optimization

4.1 Combined Benchmark + pprof

# 运行 benchmark 并生成 CPU profile
go test -bench=BenchmarkProcess -cpuprofile=cpu.prof -benchmem

# 分析
go tool pprof -http=:8081 cpu.prof

# 运行 benchmark 并生成内存 profile
go test -bench=BenchmarkProcess -memprofile=mem.prof -benchmem
go tool pprof -http=:8081 mem.prof

4.2 benchstat for Comparing Test Results

go install golang.org/x/perf/cmd/benchstat@latest

# 优化前
go test -bench=. -count=10 > old.txt

# 修改代码后
go test -bench=. -count=10 > new.txt

# 对比
benchstat old.txt new.txt

Output example:

name       old time/op    new time/op    delta
Process-8    4.50ms ± 2%    1.20ms ± 1%  -73.3%  (p=0.000 n=10+10)

name       old alloc/op   new alloc/op   delta
Process-8    1.20MB ± 0%    0.04MB ± 0%  -96.7%  (p=0.000 n=10+10)

5. Common Optimization Techniques

5.1 Reduce Memory Allocations

// 差:每次调用都分配
func bad() []byte {
    buf := make([]byte, 1024)
    return buf
}

// 好:使用 sync.Pool
var bufPool = sync.Pool{
    New: func() interface{} { return make([]byte, 1024) },
}
func good() []byte {
    buf := bufPool.Get().([]byte)
    defer bufPool.Put(buf)
    // 使用 buf...
    return buf
}

// 好:预分配 slice
func preallocSlice(n int) []int {
    result := make([]int, 0, n) // 预知容量
    for i := 0; i < n; i++ {
        result = append(result, i)
    }
    return result
}

5.2 String Concatenation Optimization

// 基准测试对比(拼接10000次)

// 慢:+ 拼接 (~50ms, 大量内存分配)
func concatPlus(n int) string {
    s := ""
    for i := 0; i < n; i++ {
        s += "a"
    }
    return s
}

// 中:fmt.Sprintf (~5ms)
func concatSprintf(n int) string {
    return fmt.Sprintf("%s%s", a, b)
}

// 快:strings.Builder (~0.01ms, 推荐)
func concatBuilder(n int) string {
    var b strings.Builder
    b.Grow(n) // 预分配
    for i := 0; i < n; i++ {
        b.WriteString("a")
    }
    return b.String()
}

// 快:bytes.Buffer (~0.01ms)
func concatBuffer(n int) string {
    var buf bytes.Buffer
    buf.Grow(n)
    for i := 0; i < n; i++ {
        buf.WriteString("a")
    }
    return buf.String()
}

// 特殊场景:strings.Join(已知所有片段)
func concatJoin(parts []string) string {
    return strings.Join(parts, "")
}

5.3 Avoid Unnecessary Reflection

// 慢:反射
func setFieldReflect(obj interface{}, name string, value interface{}) {
    v := reflect.ValueOf(obj).Elem()
    f := v.FieldByName(name)
    f.Set(reflect.ValueOf(value))
}

// 快:直接赋值或使用接口
type Setter interface {
    SetName(string)
}
func setField(obj Setter, name string) {
    obj.SetName(name) // 接口方法调用比反射快 ~100 倍
}

5.4 Judicious Use of Goroutines

// 差:为每个小任务创建 goroutine
for _, item := range items {
    go process(item) // 百万个 goroutine,调度开销大
}

// 好:Worker Pool 控制并发数
func processAll(items []Item) {
    sem := make(chan struct{}, runtime.NumCPU())
    var wg sync.WaitGroup
    for _, item := range items {
        wg.Add(1)
        sem <- struct{}{} // 限制并发
        go func(it Item) {
            defer wg.Done()
            defer func() { <-sem }()
            process(it)
        }(item)
    }
    wg.Wait()
}

5.5 Reduce Lock Contention

// 差:全局大锁
var mu sync.Mutex
var globalMap = make(map[string]int)

// 好:分片锁(Sharded Map)
const shardCount = 32
type ShardedMap struct {
    shards [shardCount]struct {
        sync.RWMutex
        data map[string]int
    }
}

func (m *ShardedMap) getShard(key string) int {
    h := fnv.New32a()
    h.Write([]byte(key))
    return int(h.Sum32()) % shardCount
}

func (m *ShardedMap) Set(key string, val int) {
    idx := m.getShard(key)
    m.shards[idx].Lock()
    m.shards[idx].data[key] = val
    m.shards[idx].Unlock()
}

5.6 Struct Field Alignment

// 差:字段顺序导致内存浪费(padding)
type Bad struct {
    a bool   // 1B + 7B padding
    b int64  // 8B
    c bool   // 1B + 7B padding
} // 总共 24B

// 好:按大小降序排列
type Good struct {
    b int64  // 8B
    a bool   // 1B
    c bool   // 1B + 6B padding
} // 总共 16B

// 检查工具
// go install golang.org/x/tools/go/analysis/passes/fieldalignment/cmd/fieldalignment@latest
// fieldalignment -fix ./...

6. Practical Example: Optimizing a Slow API Endpoint

问题: GET /api/users 平均响应 500ms

Step 1: 采集 CPU Profile
  go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
  (同时对接口进行压测 wrk/hey/ab)

Step 2: 查看 Top 热点
  (pprof) top
  → 发现 encoding/json.Marshal 占 40%
  → 发现 database/sql.Query 占 30%

Step 3: 查看具体代码
  (pprof) list handleUsers
  → 每次请求都序列化全量用户数据
  → 每次请求都执行 SELECT * 无分页

Step 4: 优化
  1. 添加分页 (LIMIT/OFFSET)
  2. 使用 jsoniter 替代 encoding/json
  3. 对热点数据添加 Redis 缓存
  4. 使用 sync.Pool 复用 buffer

Step 5: 对比
  优化前: 500ms, 100 allocs/op, 5MB/op
  优化后:  50ms,  20 allocs/op, 200KB/op

Quick Reference

Command Purpose
go build -gcflags="-m" View escape analysis
go test -bench=. -benchmem Run benchmarks
go test -bench=. -cpuprofile=cpu.prof Generate CPU profile
go test -bench=. -memprofile=mem.prof Generate memory profile
go tool pprof -http=:8081 cpu.prof Web UI analysis
go tool pprof profile_url Command-line analysis
go tool trace trace.out Trace analysis
GODEBUG=gctrace=1 ./app Print GC logs
GOGC=200 Adjust GC trigger threshold
GOMEMLIMIT=1GiB Set soft memory limit

主题测试文章,只做测试使用。发布者:Walker,转转请注明出处:https://walker-learn.xyz/archives/6786

(0)
Walker的头像Walker
上一篇 11 hours ago
下一篇 19 hours ago

Related Posts

EN
简体中文 繁體中文 English