Golang / GoLang System Architecture and Testing Interview Questions
How do you benchmark concurrent code with testing.B and what insights does it provide?
Serial benchmarks (for i := 0; i < b.N; i++) measure single-goroutine throughput. Parallel benchmarks reveal lock contention, cache coherence issues, and true concurrent throughput — critical for shared data structures and handlers.
// Serial benchmark: single goroutine throughput func BenchmarkMapGet(b *testing.B) { m := map[string]int{"key": 1} b.ResetTimer() for i := 0; i < b.N; i++ { _ = m["key"] } } // Parallel benchmark: concurrent throughput + contention func BenchmarkSyncMapGet(b *testing.B) { var m sync.Map m.Store("key", 1) b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { // pb.Next() is goroutine-safe, replaces i < b.N m.Load("key") } }) } // Compare mutex-protected map vs sync.Map under contention type MutexMap struct { mu sync.RWMutex m map[string]int } func BenchmarkMutexMapVsSyncMap(b *testing.B) { b.Run("mutex-map", func(b *testing.B) { mm := &MutexMap{m: map[string]int{"k": 1}} b.RunParallel(func(pb *testing.PB) { for pb.Next() { mm.mu.RLock() _ = mm.m["k"] mm.mu.RUnlock() } }) }) b.Run("sync-map", func(b *testing.B) { var sm sync.Map sm.Store("k", 1) b.RunParallel(func(pb *testing.PB) { for pb.Next() { sm.Load("k") } }) }) } // Run with multiple parallelism levels: // go test -bench=BenchmarkMutexMapVsSyncMap -cpu=1,4,8,16 // -cpu controls GOMAXPROCS; shows how performance scales with CPUs // Custom metric reporting b.SetParallelism(10) // GOMAXPROCS * 10 goroutines b.ReportMetric(float64(b.N)/b.Elapsed().Seconds(), "rps") b.ReportMetric(float64(contention)/float64(b.N), "contentions/op")
More Related questions...