Lab 14: Performance Tuning
Overview
Step 1: GOMAXPROCS — CPU Parallelism
package main
import (
"fmt"
"runtime"
"sync"
"time"
)
func cpuIntensiveWork(n int) float64 {
result := 0.0
for i := 0; i < n; i++ {
result += float64(i) * 1.0001
}
return result
}
func parallelWork(procs int) time.Duration {
runtime.GOMAXPROCS(procs)
var wg sync.WaitGroup
start := time.Now()
numTasks := runtime.NumCPU() * 2
for i := 0; i < numTasks; i++ {
wg.Add(1)
go func() {
defer wg.Done()
cpuIntensiveWork(1_000_000)
}()
}
wg.Wait()
return time.Since(start)
}
func main() {
fmt.Printf("NumCPU: %d\n", runtime.NumCPU())
fmt.Printf("Current GOMAXPROCS: %d\n", runtime.GOMAXPROCS(0))
// GOMAXPROCS controls how many OS threads run Go code concurrently
// Default: runtime.NumCPU()
// Set via env: GOMAXPROCS=4 go run main.go
// Set programmatically:
old := runtime.GOMAXPROCS(4)
fmt.Printf("Set GOMAXPROCS=4 (was %d)\n", old)
runtime.GOMAXPROCS(old) // restore
}Step 2: GOGC Tuning
Step 3: GOMEMLIMIT (Go 1.19+)
Step 4: Goroutine Stack Growth
Step 5: Benchmark Comparison
Step 6: TCP Socket Options
Step 7: GC Stats + Memory Limits Demo
Step 8: Capstone — Systematic Performance Analysis
Summary
Knob
How to Set
Effect
Last updated
