Golang Benchmark
Samuel BertheCommunityCreated by samberDistributed by Samuel Berthe
- Skill
- Tool integration
- Software development
- MIT
- Low risk
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a rigorous methodology for measuring Go performance. It covers the entire lifecycle: writing benchmarks with proper conventions, executing them under controlled conditions, generating profiles (CPU, memory, trace), and performing statistical comparisons using benchstat to distinguish real performance gains from noise. It emphasizes statistical significance and reproducible measurement over anecdotal testing.
What it does
- Guides the creation of Go benchmarks using standard naming and file conventions.
- Provides commands for running benchmarks with memory reporting and statistical iteration counts.
- Facilitates the generation of CPU, memory, and execution trace profiles for deep analysis.
- Uses benchstat to perform A/B comparisons with statistical confidence intervals.
- Offers strategies for integrating performance regression detection into CI pipelines.
- Explains how to document performance improvements in commit messages using benchmark data.
When to use it
- When you need to measure the performance impact of a code change with statistical rigor.
- When investigating performance bottlenecks using CPU or memory profiling.
- When setting up automated performance regression gating in CI.
- When comparing multiple optimization variants to identify the most effective approach.
- When you need to verify that a code change has a measurable impact before committing.
Advantages
- Promotes statistical rigor, preventing misleading conclusions from single benchmark runs.
- Standardizes benchmark file naming and function ordering for better maintainability.
- Integrates seamlessly with standard Go tooling and performance analysis utilities.
- Provides clear guidance on avoiding common pitfalls like noisy neighbors and dead-code elimination.
- Enables data-driven performance documentation in git history.
Usage examples
- “How do I run my benchmarks 10 times to ensure statistical significance?”
- The agent will provide the command: go test -run='^$' -bench=. -benchmem -count=10 ./pkg/...
- “Compare my current changes against the main branch for performance regressions.”
- The agent will guide you to use benchdiff to compare git refs, ensuring results are cached and statistically compared.
- “How do I generate and analyze a CPU profile for my benchmark?”
- The agent will show how to run go test with -cpuprofile, followed by using go tool pprof to interactively analyze the resulting file.
- “How should I format my commit message when I optimize a function?”
- The agent will provide a template including the hardware context and the benchstat output table to prove the performance gain.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/samber/golang-benchmark/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip golang-benchmark.zip -d .agents/skills
Documentation by samber
Persona: You are a Go performance measurement engineer. You never draw conclusions from a single benchmark run — statistical rigor and controlled conditions are prerequisites before any optimization decision.
Thinking mode: Reason as thoroughly as possible for benchmark analysis, profile interpretation, and performance comparison tasks — deep reasoning prevents misinterpreting profiling data and ensures statistically sound conclusions. On Claude Code, use ultrathink to trigger extended thinking explicitly.
Dependencies:
benchstat:
go install golang.org/x/perf/cmd/benchstat@latest
Go Benchmarking & Performance Measurement
Performance improvement does not exist without measures — if you can measure it, you can improve it.
This skill covers the full measurement workflow: write a benchmark, run it, profile the result, compare before/after with statistical rigor, and track regressions in CI. For optimization patterns to apply after measurement, → See samber/cc-skills-golang@golang-performance skill. For pprof setup on running services, → See samber/cc-skills-golang@golang-troubleshooting skill.
Writing Benchmarks
File and Ordering Conventions
Benchmark functions live in a _bench_test.go file named after the source file under benchmark, not after the individual function — parser.go -> parser_bench_test.go, containing BenchmarkParse, BenchmarkEncode, etc., not a separate benchmarkparse_test.go per function.
Keeping benchmarks in their own file (instead of mixed into
parser_test.go) keepsgo test -bench=. ./pkg/parseroutput free of unrelatedTest*noise.It separates fixtures sized for measurement (large inputs, long-lived setup) from those sized for correctness — the two rarely share the same shape.
The file still follows Go's one-test-file-per-source-file convention (→ See
samber/cc-skills-golang@golang-testingskill), just with the_benchsuffix marking its narrower purpose.
Order Benchmark* functions inside parser_bench_test.go to mirror the order of the functions/methods they measure in parser.go — a reader comparing the two files top to bottom should find BenchmarkParse at the same relative position as Parse.
b.Loop() (Go 1.24+) — preferred
For Go 1.24+, prefer b.Loop() for new benchmarks. It times only the loop body and keeps function arguments/results alive, which reduces dead-code-elimination mistakes.
func BenchmarkParse(b *testing.B) {
data := loadFixture("large.json") // setup — excluded from timing
for b.Loop() {
Parse(data) // compiler cannot eliminate this call
}
}Legacy b.N loops still compile and are fine to keep when preserving existing benchmarks or supporting Go <1.24. They are easier to get wrong: setup may need b.ResetTimer(), and results may need a sink if the compiler can eliminate the work. Go 1.26 fixed an earlier b.Loop() inlining limitation — benchmarks on 1.24–1.25 already benefit from b.Loop() but may miss inlining optimizations that 1.26 delivers.
Go 1.27's size-specialized allocator changes allocation-heavy benchmark baselines (faster sub-80-byte allocations, larger binaries) independent of any code change. Treat a benchstat comparison that straddles the Go 1.26→1.27 toolchain boundary as measuring the toolchain, not the code — rerun the "before" benchmark on the same toolchain as "after" before trusting the delta.
Memory tracking
func BenchmarkAlloc(b *testing.B) {
b.ReportAllocs() // or run with -benchmem flag
var sink []byte
for b.Loop() {
sink = make([]byte, 1024)
}
_ = sink
}b.ReportMetric() adds custom metrics (e.g., throughput):
b.ReportMetric(float64(totalBytes)/b.Elapsed().Seconds(), "bytes/s") // b.Elapsed() is only valid inside b.Loop()Sub-benchmarks and table-driven
func BenchmarkEncode(b *testing.B) {
for _, size := range []int{64, 256, 4096} {
b.Run(fmt.Sprintf("size=%d", size), func(b *testing.B) {
data := make([]byte, size)
for b.Loop() {
Encode(data)
}
})
}
}Running Benchmarks
go test -bench=BenchmarkEncode -benchmem -count=10 ./pkg/... | tee bench.txt| Flag | Purpose |
|---|---|
-bench=. | Run all benchmarks (regexp filter) |
-benchmem | Report allocations (B/op, allocs/op) |
-count=10 | Run 10 times for statistical significance |
-benchtime=3s | Minimum time per benchmark (default 1s) |
-cpu=1,2,4 | Run with different GOMAXPROCS values |
-cpuprofile=cpu.prof | Write CPU profile |
-memprofile=mem.prof | Write memory profile |
-trace=trace.out | Write execution trace |
Output format: BenchmarkEncode/size=64-8 5000000 230.5 ns/op 128 B/op 2 allocs/op — the -8 suffix is GOMAXPROCS, ns/op is time per operation, B/op is bytes allocated per op, allocs/op is heap allocation count per op.
Comparing Optimization Variants in Parallel
When several competing optimization hypotheses exist for the same bottleneck, implement each variant in its own isolated worktree via a separate sub-agent, so their code changes never collide in the shared working tree.
Run the benchmarks serially, not concurrently. Concurrent benchmark runs share the same CPU — the noisy-neighbor effect contaminates ns/op and reintroduces the exact statistical noise -count and benchstat exist to eliminate. Implementing in parallel is safe (isolated worktrees, no file contention); measuring in parallel is not (shared hardware, real contention). Run each variant's benchmark one at a time, back in the main tree or sequentially per worktree.
Compare every variant's benchstat output against the same baseline report, keep the winner, and remove the worktrees for the rest.
Documenting Results in Commits
Paste benchstat output in the commit body when the change has a measurable performance impact. This documents why an optimization was made, prevents future readers from reverting it, and lets reviewers verify the claim without re-running benchmarks.
Commit format:
perf(parser): reduce Parse allocations 50% with sync.Pool
Replace per-call []byte allocation with a pooled buffer.
goos: linux / goarch: amd64 / cpu: AMD Ryzen 9 5950X
│ old │ new │
│ sec/op │ sec/op vs base │
Parse-32 4.592µ ± 2% 3.041µ ± 1% -33.78% (p=0.000 n=10)
│ old │ new │
│ B/op │ B/op vs base │
Parse-32 1.024Ki ± 0% 0.512Ki ± 0% -50.00% (p=0.000 n=10)
│ old │ new │
│ allocs/op │ allocs/op vs base │
Parse-32 12.00 ± 0% 6.000 ± 0% -50.00% (p=0.000 n=10)Rules:
Only include benchmarks directly affected by the change — strip unrelated rows
Never paste results with
~(no statistical significance) — the improvement cannot be claimedInclude the hardware context line (
goos/goarch/cpu) so results are reproducibleUse
perf(scope):commit type for performance-only changes
Profiling from Benchmarks
Generate profiles directly from benchmark runs — no HTTP server needed:
# CPU profile
go test -bench=BenchmarkParse -cpuprofile=cpu.prof ./pkg/parser
go tool pprof cpu.prof
# Memory profile (alloc_objects shows GC churn, inuse_space shows leaks)
go test -bench=BenchmarkParse -memprofile=mem.prof ./pkg/parser
go tool pprof -alloc_objects mem.prof
# Execution trace
go test -bench=BenchmarkParse -trace=trace.out ./pkg/parser
go tool trace trace.outFor full pprof CLI reference (all commands, non-interactive mode, profile interpretation), see pprof Reference. For execution trace interpretation, see Trace Reference. For statistical comparison, see benchstat Reference.
Reference Files
pprof Reference — Interactive and non-interactive analysis of CPU, memory, and goroutine profiles. Full CLI commands, profile types (CPU vs allocobjects vs inuse_space), web UI navigation, and interpretation patterns. Use this to dive deep into _where time and memory are being spent in your code.
benchstat Reference — Statistical comparison of benchmark runs with rigorous confidence intervals and p-value tests. Covers output reading, filtering old benchmarks, interleaving results for visual clarity, and regression detection. Use this when you need to prove a change made a meaningful performance difference, not just a lucky run.
Trace Reference — Execution tracer for understanding when and why code runs. Visualizes goroutine scheduling, garbage collection phases, network blocking, and custom span annotations. Use this when pprof (which shows where CPU goes) isn't enough — you need to see the timeline of what happened.
Diagnostic Tools — Quick reference for ancillary tools: fieldalignment (struct padding waste), GODEBUG (runtime logging flags), fgprof (frame graph profiles), race detector (concurrency bugs), and others. Use this when you have a specific symptom and need a focused diagnostic — don't reach for pprof if a simpler tool already answers your question.
Compiler Analysis — Low-level compiler optimization insights: escape analysis (when values move to the heap), inlining decisions (which function calls are eliminated), SSA dump (intermediate representation), and assembly output. Use this when benchmarks show allocations you didn't expect, or when you want to verify the compiler did what you intended.
CI Regression Detection — Automated performance regression gating in CI pipelines. Covers three tools (benchdiff for quick PR comparisons, cob for strict threshold-based gating, gobenchdata for long-term trend dashboards), noisy neighbor mitigation strategies (why cloud CI benchmarks vary 5-10% even on quiet machines), and self-hosted runner tuning to make benchmarks reproducible. Use this when you want to ensure pull requests don't silently slow down your codebase — detecting regressions early prevents shipping performance debt.
Investigation Session — Production performance troubleshooting workflow combining Prometheus runtime metrics (heap size, GC frequency, goroutine counts), PromQL queries to correlate metrics with code changes, runtime configuration flags (GODEBUG env vars to enable GC logging), and cost warnings (when you're hitting performance tax). Use this when production benchmarks look good but real traffic behaves differently.
Prometheus Go Metrics Reference — Complete listing of Go runtime metrics actually exposed as Prometheus metrics by
prometheus/client_golang. Covers 30 default metrics, 40+ optional metrics (Go 1.17+), process metrics, and common PromQL queries. Distinguishes betweenruntime/metrics(Go internal data) and Prometheus metrics (what you scrape from/metrics). Use this when setting up monitoring dashboards or writing PromQL queries for production alerts.
Cross-References
→ See
samber/cc-skills-golang@golang-performanceskill for optimization patterns to apply after measuring ("if X bottleneck, apply Y")→ See
samber/cc-skills-golang@golang-troubleshootingskill for pprof setup on running services (enable, secure, capture), Delve debugger, GODEBUG flags, root cause methodology→ See
samber/cc-skills-golang@golang-observabilityskill for everyday always-on monitoring, continuous profiling (Pyroscope), distributed tracing (OpenTelemetry)→ See
samber/cc-skills-golang@golang-testingskill for general testing practices→ See
samber/cc-skills@promql-cliskill for querying Prometheus runtime metrics in production to validate benchmark findings
Files
- ATTRIBUTION.mdAdded by AutoGineer905 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md13.5 KiB
- evals/evals.json91.2 KiB
- references/benchstat.md16.0 KiB
- references/ci-regression.md11.3 KiB
- references/compiler-analysis.md11.4 KiB
- references/investigation-session.md7.7 KiB
- references/pprof.md36.7 KiB
- references/prometheus-go-metrics.md12.9 KiB
- references/tools.md3.9 KiB
- references/trace.md19.7 KiB
references/investigation-session.md
Investigation Session Setup
Tools and techniques for temporary deep-dive performance investigation — not everyday monitoring. These are things you enable for hours or days while debugging a specific issue, then disable.
Table of Contents
Setting Up a Session
Prometheus Go Runtime Collector
Key Series
PromQL Deep-Dive Queries
GC pressure
Memory leak detection
Goroutine leak detection
CPU saturation
Post-deploy regression detection
Example alerting rules
Host-Level Correlation
Cost Warnings
Setting Up a Session
Before diving into profiles, set up the environment to collect high-resolution data:
Reduce Prometheus scrape interval to <=10s on the target instance (normally 15-30s). More data points during a short investigation window reveal patterns that 30s intervals miss. Revert after investigation.
Enable pprof via environment variable — no recompile needed:
kubectl set env deployment/my-service PPROF_ENABLED=true kubectl rollout restart deployment/my-serviceEnable continuous profiling on the target instance only — not fleet-wide. Pyroscope/Parca on a single instance is manageable; on 50 replicas it overwhelms the backend.
kubectl set env deployment/my-service PYROSCOPE_ENABLED=true kubectl rollout restart deployment/my-serviceEnable debug logging via env var if needed — but only on the target instance. Debug logging has significant throughput impact:
kubectl set env deployment/my-service LOG_LEVEL=debug kubectl rollout restart deployment/my-service
Key principle: all costly debug features (pprof HTTP, continuous profiling, debug log level, trace collection) SHOULD be configurable via environment variables. This allows instant toggle without recompile. Design your application to support this from day one.
Prometheus Go Runtime Collector
The prometheus/client_golang library automatically registers collectors that expose Go runtime metrics. These are invaluable during investigation sessions — they provide a time-series view of memory, GC, goroutines, and CPU that complements point-in-time profiles.
When using prometheus/client_golang, refer to the library's official documentation to verify collector setup and available options.
Key Series
→ See prometheus-go-metrics.md for the exhaustive reference of all Go runtime metrics (verified from official sources). Note: runtime/metrics list varies by Go version — use metrics.All() at runtime for your specific Go version.
Performance note: go_memstats_* metrics internally call runtime.ReadMemStats(), which triggers a short stop-the-world pause. In Go 1.17+, the runtime/metrics collector (collectors.NewGoCollector()) uses runtime/metrics instead, which is cheaper. Prefer the modern collector in high-throughput services:
import "github.com/prometheus/client_golang/prometheus/collectors"
// Use runtime/metrics-based collector (lower overhead)
reg := prometheus.NewRegistry()
reg.MustRegister(collectors.NewGoCollector(
collectors.WithGoCollectorRuntimeMetrics(collectors.MetricsAll),
))
reg.MustRegister(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}))PromQL Deep-Dive Queries
Use these during investigation sessions with the reduced scrape interval. Each query includes what to look for and what the result means.
GC pressure
| PromQL | What to look for |
|---|---|
rate(go_gc_duration_seconds_count[5m]) | GC cycles/s. >2/s sustained = excessive allocation rate. Reduce allocations per request. |
rate(go_gc_duration_seconds_sum[5m]) / rate(go_gc_duration_seconds_count[5m]) | Average GC pause. Increasing trend = heap growing or too many pointers to scan. |
go_gc_duration_seconds{quantile="1"} | Worst-case GC pause. Spikes here cause tail latency (P99). |
Memory leak detection
| PromQL | What to look for |
|---|---|
go_memstats_alloc_bytes | Should be roughly stable under constant load. Continuous increase = memory leak. |
rate(go_memstats_alloc_bytes_total[5m]) | Allocation rate (bytes/s). Compare before/after deploy — significant increase = new allocation pattern. |
process_resident_memory_bytes - go_memstats_sys_bytes | Gap = non-Go memory (cgo, mmap). Growing gap = non-Go leak. |
Goroutine leak detection
| PromQL | What to look for |
|---|---|
go_goroutines | Should correlate with load. Growing independently of traffic = leak. |
delta(go_goroutines[1h]) | Net goroutine change over 1h. Positive without load increase = leak. |
CPU saturation
| PromQL | What to look for |
|---|---|
rate(process_cpu_seconds_total[5m]) | CPU cores consumed. Compare to GOMAXPROCS. |
rate(process_cpu_seconds_total[5m]) / <GOMAXPROCS> | CPU utilization ratio. >0.8 sustained = CPU-saturated. |
Post-deploy regression detection
| PromQL | What to look for |
|---|---|
rate(go_memstats_alloc_bytes_total[5m]) | Compare before/after deploy window. Significant increase = new allocation pattern introduced. |
histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m])) | P99 latency increase after deploy = performance regression. Requires app-level histogram. |
Example alerting rules
# GC taking too much time
- alert: HighGCPauseTime
expr: rate(go_gc_duration_seconds_sum[5m]) / rate(go_gc_duration_seconds_count[5m]) > 0.01
for: 10m
annotations:
summary: "Average GC pause >10ms — reduce allocations or tune GOGC"
# Goroutine leak
- alert: GoroutineLeak
expr: go_goroutines > 10000
for: 5m
annotations:
summary: "Goroutine count >10K — check for leaked goroutines"
# Memory approaching container limit
- alert: MemoryNearLimit
expr: predict_linear(process_resident_memory_bytes[1h], 3600) > <container_limit_bytes>
for: 15m
annotations:
summary: "RSS projected to exceed container limit within 1h"Adjust thresholds to your application — a data pipeline has different baselines than an API server.
Host-Level Correlation
Go runtime metrics alone don't show the full picture. Host-level metrics reveal whether the problem is in your application or the infrastructure.
node_exporter— host CPU, memory, disk I/O, network. Correlate with Go app metrics: highnode_cpu_seconds_totalwith lowprocess_cpu_seconds_total= noisy neighbor, not your app.process-exporter— per-process metrics on Linux. Useful when multiple Go services share a host.
Cost Warnings
Profiles and traces are expensive to collect. Keep them short-term and localized:
pprof CPU profiling — CPU-intensive during the capture window. Don't run 30s profiles back-to-back in production. Space them out.
Pyroscope continuous profiling — ~2-5% CPU overhead per instance, always-on. At scale (hundreds of instances), this adds up in compute cost and backend storage. Enable on a subset of instances or on-demand via environment variable. → See
samber/cc-skills-golang@golang-observabilityskill for Pyroscope setup.Execution traces — generate large files quickly (MB/s). Capture 5-10s max. Longer traces are unwieldy and slow to analyze.
Debug log level — significant throughput impact due to allocation and I/O overhead. Never leave on permanently.
All costly features SHOULD be toggleable via environment variables for instant on/off without recompile. Design for this from day one.
Requirements and compatibility
Written for: Claude Code, OpenAI Codex
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Declares allowed tools, Claude Code frontmatter
The author says: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
Security
What our scanner noticed· Low risk
- Instructions that use the network
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- samber
- Publisher
- Samuel Berthe (Community)
- Distributed by
- Samuel Berthe
- Source
- samber/cc-skills-golang · skills/golang-benchmark · commit bb1d43d
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by samber or Samuel Berthe.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download golang-benchmark.zip