Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

性能分析與除錯

Go 性能分析、Trace 追蹤、Debug 除錯與問題排查。

📊 性能分析

完整指南

🔍 Trace 追蹤

追蹤剖析

🐛 除錯工具

Debugger

🔧 問題排查

死鎖分析

💡 性能分析工具

pprof

  1. CPU Profiling

    import _ "net/http/pprof"
    
    go func() {
        log.Println(http.ListenAndServe("localhost:6060", nil))
    }()
    
  2. Memory Profiling

    go tool pprof http://localhost:6060/debug/pprof/heap
    
  3. Goroutine Profiling

    go tool pprof http://localhost:6060/debug/pprof/goroutine
    

trace

  1. 啟用 trace

    import "runtime/trace"
    
    f, _ := os.Create("trace.out")
    trace.Start(f)
    defer trace.Stop()
    
  2. 分析 trace

    go tool trace trace.out
    

🔬 性能優化技巧

CPU 優化

  1. 減少 CPU 使用

    • 避免不必要的計算
    • 使用更高效的算法
    • 併發處理
  2. 減少鎖競爭

    • 細粒度鎖
    • 無鎖數據結構
    • Channel 代替鎖

記憶體優化

  1. 減少分配

    • 對象池 sync.Pool
    • 預分配 slice
    • 字符串拼接用 strings.Builder
  2. 減少 GC 壓力

    • 復用對象
    • 減小對象大小
    • 避免內存洩漏

並發優化

  1. Goroutine 管理

    • 控制 Goroutine 數量
    • Worker Pool 模式
    • 使用 context 控制生命週期
  2. Channel 優化

    • 選擇合適的緩衝大小
    • 及時關閉 Channel
    • 避免 Channel 洩漏

🐛 常見問題

Goroutine 洩漏

// 錯誤:Goroutine 永遠阻塞
func leak() {
    ch := make(chan int)
    go func() {
        ch <- 1  // 永遠阻塞
    }()
}

// 正確:使用 context 控制
func noLeak(ctx context.Context) {
    ch := make(chan int)
    go func() {
        select {
        case ch <- 1:
        case <-ctx.Done():
            return
        }
    }()
}

死鎖檢測

// 使用 runtime 檢測
func main() {
    runtime.SetMutexProfileFraction(1)
    runtime.SetBlockProfileRate(1)
}

Race Condition

# 開啟 race detector
go run -race main.go
go test -race

最後更新: 2025-12-01