Benchmarking et Performance Go

VérifiéPrudence

Rédigez des benchmarks Go corrects, mesurez, optimisez les chemins chauds et prouvez les améliorations avec benchstat.

Spar Skills Guide Bot
DeveloppementIntermédiaire
22/07/2026
Claude CodeCursorCodex
#go#benchmarking#performance#profiling#pprof

Recommandé pour

Synthèse automatique

Ce skill guide la rédaction de benchmarks Go corrects, la mesure via -benchmem et pprof, l'optimisation des chemins critiques, puis la preuve du gain par benchstat avant/après.

Points forts

  • Fournit un modèle de benchmark Go 1.24+ correct (b.Loop, ReportAllocs, variable sink pour éviter l'élimination de code mort)
  • Impose une preuve statistique du gain avec benchstat et le rejet des régressions sur les allocations
  • Liste les optimisations classiques par ordre de coût croissant (allocations, réflexion, boucles, algorithme)
  • Cadre explicitement quand ne pas optimiser le code froid

Limites

  • Suppose une configuration mise (mise run bench, bench:baseline, bench:compare) déjà présente dans le dépôt
  • Cible Go 1.24+ pour b.Loop ; les versions antérieures nécessitent la boucle b.N classique
  • Ne couvre pas les benchmarks de bout en bout ou multi-services, seulement les benchmarks unitaires Go
Quand l'utiliser

À utiliser lorsqu'on écrit un benchmark Go ou qu'on cherche à mesurer et optimiser la performance d'une fonction sur un chemin critique.

Quand l'éviter

À éviter pour du code froid ou lorsque la lisibilité prime sur le micro-gain, et hors d'un projet Go.

Analyse de sécurité

Prudence
Score qualité88/100

The skill is purely instructional Go performance guidance. Commands shown are standard, legitimate developer tooling (go test, pprof, benchstat) with no destructive, exfiltrating, or obfuscated actions and no secret handling. It is rated caution only because it directs execution of build/test/benchmark tooling and repo-defined mise tasks without declaring allowed-tools, so the actual command surface depends on the host repository.

Points d'attention
  • •Includes shell commands (go test -bench, go tool pprof, mise run bench/bench:baseline/bench:compare) that an agent may execute, but no allowed-tools are declared to scope this
  • •Assumes repo-specific mise tasks (bench, bench:baseline, bench:compare) whose behavior is not shown and depends on the host repo
Comment cette analyse est faite

Exemples

Benchmark a hot function
Write a correct benchmark for distance() in internal/search and report allocs per op.
Optimize with proof
Our candidate search feels slow — profile it, optimize the hot path, and prove the gain with benchstat before/after.
Reduce allocations
Check the allocations in the distance function's benchmark and reduce them without changing behavior.

name: go-benchmark description: Use when writing Go benchmarks or when asked to measure/optimize/improve the performance of a function — establishes correct benchmarks, measures with -benchmem and pprof, optimizes hot paths, and proves the gain (and no regression) with benchstat.

Go Benchmarking & Performance

Goal: only optimize what's measured. Write a correct benchmark, measure, optimize, and prove the improvement with benchstat before/after.

When to benchmark (the right targets)

Benchmark a function when: it's on a hot path (called in tight loops — e.g. the candidate-search and image-distance core of the port), it allocates heavily, or someone claims it's "slow". Do NOT micro-optimize cold code — clarity wins there (see go-style-guide).

Writing a correct benchmark (Go 1.24+)

func BenchmarkDistance(b *testing.B) {
    img := loadFixture()      // setup OUTSIDE the loop
    b.ReportAllocs()          // always report allocs
    b.ResetTimer()            // if setup was non-trivial
    for b.Loop() {            // Go 1.24+: not `for i := 0; i < b.N; i++`
        sink = distance(img)  // assign to a package-level sink…
    }
}

var sink int // …to stop the compiler eliminating the call
  • b.Loop() (Go 1.24+) — keeps setup/cleanup out of the timed region automatically.
  • b.ReportAllocs() — allocs/op is usually the real lever.
  • Prevent dead-code elimination: store results in a package-level sink.
  • Table-driven sub-benchmarks with b.Run(name, …) for input sizes.
  • b.RunParallel for contention; b.SetBytes(n) for throughput (MB/s).

Measure

mise run bench                 # go test -bench -benchmem ./...
go test -bench=Distance -benchmem -cpuprofile cpu.prof -memprofile mem.prof ./internal/...
go tool pprof -top cpu.prof    # find the hot frames / allocations

Optimize (typical levers, cheapest first)

  1. Reduce allocations: preallocate slices/maps with known size, reuse buffers (sync.Pool, bytes.Buffer), avoid []byte↔string copies (strings.Builder).
  2. Avoid reflection / interface boxing on hot paths; use generics or concrete types.
  3. Hoist work out of loops; precompute; use slices/maps helpers.
  4. Algorithmic improvement (better complexity) beats micro-tuning — escalate to algo-architect if the win is algorithmic.

Prove the gain (mandatory)

mise run bench:baseline        # save baseline BEFORE changing code
# …optimize…
mise run bench:compare         # benchstat baseline vs new → shows %delta + significance

Keep a change only if benchstat shows a statistically significant improvement (and no regression in allocs or other benchmarks). Commit the benchmark alongside the optimization.

Notes

  • Benchmark artifacts (bench*.txt, *.prof) are gitignored and cleaned by repo-janitor.
  • Don't sacrifice clarity for a tiny gain — measure first, and only optimize where it matters.

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/go-benchmarking-performance-mrwak9qz/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/go-benchmarking-performance-mrwak9qz' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/go-benchmarking-performance-mrwak9qz/download' --output '.skill-downloads/go-benchmarking-performance-mrwak9qz/SKILL.md.part' && mv '.skill-downloads/go-benchmarking-performance-mrwak9qz/SKILL.md.part' '.skill-downloads/go-benchmarking-performance-mrwak9qz/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/go-benchmarking-performance-mrwak9qz/SKILL.md' && test -s '.skill-downloads/go-benchmarking-performance-mrwak9qz/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/go-benchmark' && cp -R '.skill-downloads/go-benchmarking-performance-mrwak9qz' '.claude/skills/go-benchmark'

Cursor
test -f '.skill-downloads/go-benchmarking-performance-mrwak9qz/SKILL.md' && test -s '.skill-downloads/go-benchmarking-performance-mrwak9qz/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/go-benchmark' && cp -R '.skill-downloads/go-benchmarking-performance-mrwak9qz' '.cursor/skills/go-benchmark'

Codex
test -f '.skill-downloads/go-benchmarking-performance-mrwak9qz/SKILL.md' && test -s '.skill-downloads/go-benchmarking-performance-mrwak9qz/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/go-benchmark' && cp -R '.skill-downloads/go-benchmarking-performance-mrwak9qz' '.agents/skills/go-benchmark'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/go-benchmarking-performance-mrwak9qz'

openskills read 'go-benchmarking-performance-mrwak9qz'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/go-benchmarking-performance-mrwak9qz/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires