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")
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
