notque/vexjoy-agent / skills/programming/programming
programming
FlaggedLanguage rules, workflows, and tooling: Go, Python, Rust, Kotlin, Swift, PHP, TypeScript type checks and debugging, OpenStack Python, MCP local-docs servers, Node.js backend APIs.
references/go/testing/go-benchmark-and-concurrency.md
View on GitHub# Go Benchmarks and Concurrency Testing Reference
Detailed examples for benchmarks, synctest, and race detection. See SKILL.md for methodology.
---
## Benchmarks with b.Loop() (Go 1.24+)
### Why b.Loop() Over b.N
The old `for i := 0; i < b.N; i++` pattern is deprecated. Use `b.Loop()` because:
1. **Prevents Dead Code Elimination**: Compiler detects `b.Loop()` and prevents inlining
2. **Automatic Timer Management**: Integrated `b.ResetTimer()` at start, `b.StopTimer()` at end
3. **More Accurate Results**: Prevents compiler optimizations that make benchmarks artificially fast
4. **Faster Execution**: Single-pass ramp-up instead of multiple function calls with ramping b.N
### Complete Benchmark Example
```go
func BenchmarkStringBuilder(b *testing.B) {
words := []string{"hello", "world", "from", "go", "benchmark"}
b.Run("strings.Builder", func(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
var sb strings.Builder
for _, word := range words {
sb.WriteString(word)
sb.WriteString(" ")
}
_ = sb.String()
}
})
b.Run("bytes.Buffer", func(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
var buf bytes.Buffer
for _, word := range words {
buf.WriteString(word)
buf.WriteString(" ")
}
_ = buf.String()
}
})
b.Run("string concatenation", func(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
result := ""
for _, word := range words {
result += word + " "
}
_ = result
}
})
}
```
### Benchstat Comparison Workflow
```bash
# Install benchstat
go install golang.org/x/perf/cmd/benchstat@latest
# Baseline measurements (run 10 times for statistical significance)
go test -bench=. -count=10 ./... > old.txt
# Make changes...
# New measurements
go test -bench=. -count=10 ./... > new.txt
# Compare
benchstat old.txt new.txt
```
### Running Benchmarks
```bash
go test -bench=. -benchmem ./... # All benchmarks with memory
go test -bench=BenchmarkStringBuilder -benchmem ./... # Specific benchmark
go test -cpuprofile=cpu.prof -memprofile=mem.prof -bench=. ./... # With profiling
```
---
## synctest: Deterministic Concurrency Testing (Go 1.25+)
The `testing/synctest` package provides deterministic testing for concurrent code with virtual time.
### Core Concepts
**Bubble**: An isolated execution context with its own virtualized clock.
- All goroutines started within the bubble are part of it
- The clock only advances when all goroutines are "durably blocked"
- Initial time: midnight UTC 2000-01-01
**Durably Blocked**: A goroutine is durably blocked when:
- It is blocked (channel receive, `time.Sleep`, etc.)
- Can only be unblocked by another goroutine in the same bubble
- Cannot be unblocked by external events
### Key API
```go
import "testing/synctest"
// Execute function in bubble with virtual time
synctest.Test(t, func(t *testing.T) {
// Test code with virtual time
})
// Wait for all goroutines to be durably blocked
synctest.Wait()
```
Go 1.27 additions: `synctest.Sleep(d)` sleeps on the fake clock and then waits for the bubble to settle (replaces `time.Sleep(d); synctest.Wait()`), and `httptest.NewTestServer(t, h)` serves over an in-memory network so HTTP tests can run inside a bubble. Real sockets and files do not count as durably blocked, so keep them out of the bubble.
### Example: Testing Timeouts
```go
func TestTimeout(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
done := make(chan bool)
go func() {
time.Sleep(5 * time.Second) // Instant with virtual time
done <- true
}()
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
defer cancel()
select {
case <-done:
// Completed in "5 seconds" (instant in test)
case <-ctx.Done():
t.Fatal("timeout waiting for goroutine")
}
})
}
```
### Benefits
1. **Fast**: Virtual time means no waiting for real delays
2. **Reliable**: Deterministic execution eliminates flaky tests
3. **Safe**: Automatic deadlock detection
4. **Simple**: No manual synchronization for time-based code
### Limitations
- Cannot recognize goroutines blocked on network or I/O
- Network testing requires fake implementations (e.g., `net.Pipe()`)
- Generally provide mock implementations of network clients/servers
---
## Race Detection Patterns
### Always Run With Race Detector
```bash
go test -race -count=1 -v ./... # Full suite
go test -race -run TestConcurrentOp ./... # Specific test
```
### Common Race Condition Fix
```go
// BAD: Race condition
func TestConcurrent(t *testing.T) {
var count int
for i := 0; i < 100; i++ {
go func() {
count++ // RACE!
}()
}
}
// GOOD: Use atomic operations
func TestConcurrent(t *testing.T) {
var count atomic.Int64
var wg sync.WaitGroup
for range 100 {
wg.Go(func() { count.Add(1) }) // Go 1.25+
}
wg.Wait()
assertEqual(t, count.Load(), int64(100))
}
```
### Mock Thread Safety
When mocks are used in concurrent tests, protect shared state:
```go
type MockStore struct {
mu sync.Mutex
calls []string
}
func (m *MockStore) Get(key string) ([]byte, error) {
m.mu.Lock()
m.calls = append(m.calls, key)
m.mu.Unlock()
return nil, nil
}
func (m *MockStore) GetCalls() []string {
m.mu.Lock()
defer m.mu.Unlock()
return append([]string{}, m.calls...)
}
```
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| rea-changelog-updatemorluto/reaPrepare or rewrite REA release changelogs and GitHub release notes from pinned Git history, with verified contributor thanks and Release Please synchronization. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| academy-guideanthropics/skillsStop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials, and use cases from Claude Academy (academy.claude.com), Anthropic's learning hub. Trigger on: "how do I", "how can I", "getting started with", "what can Claude do", "teach me", "learn to use"; questions about artifacts, projects, skills, plugins, connectors, MCP; requests about rolling Claude out to a team, class, or organization; and any ask for training materials, onboarding content, or learning resources. Use it when the user is learning how to use a feature or product — not when they are mid-task and just want the task done. This skill composes with other skills: after consulting product documentation to answer how a Claude feature works, also check here for a matching course or tutorial — a docs-grounded answer and an Academy recommendation belong together. Only recommend on a strong match; never invent Academy content. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| claude-apianthropics/skillsReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens). SKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file). | Stars: 198k | Updated | Claude CodeCodex | Unverified | Install |
| doc-coauthoringanthropics/skillsGuide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |