package main
import (
"context"
"encoding/json"
"expvar"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"runtime"
"runtime/pprof"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)
func main() {
// Register handlers on DefaultServeMux
http.HandleFunc("/cpu", cpuHandler)
http.HandleFunc("/alloc", allocHandler)
http.HandleFunc("/health", healthHandler)
// Parse flags
mode := flag.String("mode", "bench", "server|bench|regress")
endpoint := flag.String("endpoint", "/cpu", "endpoint to benchmark: /cpu, /alloc")
numReqs := flag.Int("reqs", 10000, "number of requests")
conc := flag.Int("conc", 100, "concurrency")
baselineFile := flag.String("baseline", "baseline.json", "baseline metrics file")
mult := flag.Float64("mult", 1.05, "regression multiplier threshold (e.g., 1.05 = 5% worse)")
saveBaseline := flag.Bool("save-baseline", false, "save current metrics as baseline")
flag.Parse()
switch *mode {
case "server":
log.Println("Server mode:")
log.Println(" - Workloads: http://localhost:8080/cpu | /alloc | /health")
log.Println(" - pprof (flamegraphs): http://localhost:8080/debug/pprof/")
log.Println(" - CPU: http://localhost:8080/debug/pprof/profile?seconds=30")
log.Fatal(http.ListenAndServe(":8080", nil))
default:
runBenchmark(*endpoint, *numReqs, *conc, *baselineFile, *mult, *saveBaseline, *mode == "regress")
}
}
func cpuHandler(w http.ResponseWriter, r *http.Request) {
// CPU-bound workload (~5-10ms on typical machine)
const iters = 25000000
var sink int64
for i := 0; i < iters; i++ {
sink += int64(i % 17)
}
w.Header().Set("Content-Type", "text/plain")
fmt.Fprint(w, sink)
}
func allocHandler(w http.ResponseWriter, r *http.Request) {
// Allocation-bound workload (~5-10ms)
const iters = 25000
var total int64
for i := 0; i < iters; i++ {
s := make([]byte, 2048)
total += int64(len(s))
_ = s[0] // touch
}
w.Header().Set("Content-Type", "text/plain")
fmt.Fprint(w, total)
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
fmt.Fprint(w, "ok")
}
func runBenchmark(endpoint string, numReqs, conc int, baselineFile string, mult float64, saveBaseline bool, isRegress bool) {
// Start CPU profiling (flamegraphs for CPU hotspots)
cpuFile, err := os.Create("cpu.prof")
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(cpuFile)
defer pprof.StopCPUProfile()
defer cpuFile.Close()
// Baseline memstats
var m0 runtime.MemStats
runtime.ReadMemStats(&m0)
// Start server
srv := &http.Server{
Addr: ":8080",
Handler: nil, // Use DefaultServeMux
}
var serverWG sync.WaitGroup
serverWG.Add(1)
go func() {
defer serverWG.Done()
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Printf("Server error: %v", err)
}
}()
time.Sleep(200 * time.Millisecond) // Allow server to start
// Run load test
lats, totalTime := loadTest(endpoint, numReqs, conc)
// Shutdown server
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
srv.Shutdown(ctx)
cancel()
serverWG.Wait()
// Final memstats
var m1 runtime.MemStats
runtime.ReadMemStats(&m1)
deltaAllocBytes := m1.TotalAlloc - m0.TotalAlloc
allocBytesPerOp := deltaAllocBytes / uint64(numReqs)
// Compute percentiles (P95/P99 focus)
sort.Slice(lats, func(i, j int) bool { return lats[i] < lats[j] })
n := len(lats)
p95Idx := int(float64(n) * 0.95)
if p95Idx >= n {
p95Idx = n - 1
}
p99Idx := int(float64(n) * 0.99)
if p99Idx >= n {
p99Idx = n - 1
}
p95 := lats[p95Idx]
p99 := lats[p99Idx]
throughput := float64(len(lats)) / totalTime.Seconds()
// Metrics
metrics := struct {
P95Latency time.Duration `json:"p95_latency_ns"`
P99Latency time.Duration `json:"p99_latency_ns"`
Throughput float64 `json:"throughput_reqs_per_s"`
AllocBytesOp uint64 `json:"alloc_bytes_per_op"`
NumReqs int `json:"num_reqs"`
TotalTime time.Duration `json:"total_time"`
DeltaAllocMB float64 `json:"delta_alloc_mb_total"`
}{
p95,
p99,
throughput,
allocBytesPerOp,
len(lats),
totalTime,
float64(deltaAllocBytes) / 1e6,
}
// Save metrics
data, _ := json.MarshalIndent(metrics, "", " ")
os.WriteFile("metrics.json", data, 0644)
log.Printf("Metrics saved to metrics.json")
log.Printf("P95: %v, P99: %v, TPS: %.1f, Alloc/op: %d bytes/op", p95, p99, throughput, allocBytesPerOp)
// Save baseline if requested
if saveBaseline {
os.WriteFile(baselineFile, data, 0644)
log.Printf("Baseline saved to %s", baselineFile)
return
}
// Heap profile (flamegraphs for allocation tracing)
heapFile, _ := os.Create("heap.prof")
pprof.WriteHeapProfile(heapFile)
heapFile.Close()
log.Println("=== Profiles generated ===")
log.Println(" - CPU flamegraph: go tool pprof -http=:8081 cpu.prof")
log.Println(" - Alloc flamegraph: go tool pprof -http=:8081 heap.prof")
log.Println(" - Interactive: open http://localhost:8081/flamegraph")
log.Println("=== Usage: flamegraph.pl <(go tool pprof -raw cpu.prof) > flame.svg ===")
// Regression guards (if regress mode)
if isRegress {
bdata, err := os.ReadFile(baselineFile)
if err != nil {
log.Fatalf("Failed to load baseline %s: %v", baselineFile, err)
}
var base struct {
P95Latency time.Duration `json:"p95_latency_ns"`
P99Latency time.Duration `json:"p99_latency_ns"`
Throughput float64 `json:"throughput_reqs_per_s"`
AllocBytesOp uint64 `json:"alloc_bytes_per_op"`
}
if err := json.Unmarshal(bdata, &base); err != nil {
log.Fatal("Invalid baseline:", err)
}
pass := true
// P95/P99 latency regression
if metrics.P95Latency > time.Duration(float64(base.P95Latency)*mult) {
log.Printf("FAIL P95: %v > %.2fx baseline (%.0f ns)", metrics.P95Latency, mult, float64(base.P95Latency)*mult)
pass = false
}
if metrics.P99Latency > time.Duration(float64(base.P99Latency)*mult) {
log.Printf("FAIL P99: %v > %.2fx baseline (%.0f ns)", metrics.P99Latency, mult, float64(base.P99Latency)*mult)
pass = false
}
// Throughput regression (allow mult% degradation)
minThroughput := base.Throughput / mult
if metrics.Throughput < minThroughput {
log.Printf("FAIL Throughput: %.1f < %.2fx baseline (%.1f)", metrics.Throughput, 1/mult, minThroughput)
pass = false
}
// Allocation regression
maxAlloc := uint64(float64(base.AllocBytesOp) * mult)
if metrics.AllocBytesOp > maxAlloc {
log.Printf("FAIL Alloc/op: %d > %.2fx baseline (%d)", metrics.AllocBytesOp, mult, maxAlloc)
pass = false
}
if pass {
log.Println("PASS: No performance regressions detected!")
os.Exit(0)
} else {
log.Println("FAIL: Performance regressions detected!")
os.Exit(1)
}
}
}
func loadTest(endpoint string, numReqs, conc int) ([]time.Duration, time.Duration) {
var mu sync.Mutex
var lats []time.Duration
var rem int32 = int32(numReqs)
client := &http.Client{
Timeout: 10 * time.Second,
}
start := time.Now()
var wg sync.WaitGroup
for i := 0; i < conc; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
if atomic.LoadInt32(&rem) <= 0 {
return
}
atomic.AddInt32(&rem, -1)
t0 := time.Now()
resp, err := client.Get("http://localhost:8080" + endpoint)
lat := time.Since(t0)
if err == nil {
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
mu.Lock()
lats = append(lats, lat)
mu.Unlock()
} else {
log.Printf("Request failed: %v", err)
// Don't retry for demo simplicity
}
}
}()
}
wg.Wait()
return lats, time.Since(start)
}
Usage Instructions
-
Save as profiler.go and build/run:
go mod init profiler
go mod tidy # optional, no external deps
go run profiler.go -mode=server
-
Benchmark (generates profiles + metrics):
go run profiler.go -mode=bench -endpoint=/cpu -reqs=10000 -conc=100
- Outputs:
cpu.prof (CPU flamegraphs), heap.prof (alloc flamegraphs), metrics.json
- View flamegraphs:
go tool pprof -http=:8081 cpu.prof (open http://localhost:8081/flamegraph)
- Alloc tracing:
go tool pprof -http=:8082 heap.prof (alloc samples/bytes)
-
Save baseline:
go run profiler.go -mode=bench --save-baseline
-
Regression guards (CI-friendly, exit 1 on regress):
go run profiler.go -mode=regress -endpoint=/cpu -mult=1.05
- Compares P95/P99 latency, throughput, alloc/op against
baseline.json
- Tune
-mult (e.g., 1.02 for strict 2%)
This self-contained Go program provides flamegraphs (CPU/heap via pprof), allocation tracing (heap.prof), P95/P99 latency focus (histogram percentiles), and regression guards (automated checks with exit codes). Workloads are tunable via flags/endpoints. No external deps beyond stdlib.