Skip to content

Instantly share code, notes, and snippets.

@bbengfort
Created September 19, 2022 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbengfort/44308aeab2d6def5899c7e34d189e945 to your computer and use it in GitHub Desktop.
Save bbengfort/44308aeab2d6def5899c7e34d189e945 to your computer and use it in GitHub Desktop.
Atomic vs Mutex Counter Benchmark
package counter
import (
"sync"
"sync/atomic"
)
type Counter interface {
Inc()
Load() uint64
}
type AtomicCounter struct {
value uint64
}
type LockedCounter struct {
sync.RWMutex
value uint64
}
func (c *AtomicCounter) Inc() {
atomic.AddUint64(&c.value, 1)
}
func (c *LockedCounter) Inc() {
c.Lock()
c.value++
c.Unlock()
}
func (c *AtomicCounter) Load() uint64 {
return atomic.LoadUint64(&c.value)
}
func (c *LockedCounter) Load() uint64 {
c.RLock()
defer c.RUnlock()
return c.value
}
package counter_test
import (
"math/rand"
"sync"
"sync/atomic"
. "github.com/bbengfort/x/counter"
"testing"
)
func BenchmarkCounterInc(b *testing.B) {
b.ReportAllocs()
b.Run("Atomic", func(b *testing.B) {
count := AtomicCounter{}
b.SetBytes(8)
b.ResetTimer()
for i := 0; i < b.N; i++ {
count.Inc()
}
})
b.Run("Mutex", func(b *testing.B) {
count := LockedCounter{}
b.SetBytes(8)
b.ResetTimer()
for i := 0; i < b.N; i++ {
count.Inc()
}
})
}
func BenchmarkCounterLoad(b *testing.B) {
n := rand.Intn(1e6)
b.Run("Atomic", func(b *testing.B) {
count := AtomicCounter{}
for i := 0; i < n; i++ {
count.Inc()
}
b.SetBytes(8)
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = count.Load()
}
})
b.Run("Mutex", func(b *testing.B) {
count := LockedCounter{}
for i := 0; i < n; i++ {
count.Inc()
}
b.SetBytes(8)
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = count.Load()
}
})
}
BenchmarkCounterInc/Atomic-10 170998743 6.881 ns/op 1162.54 MB/s 0 B/op 0 allocs/op
BenchmarkCounterInc/Mutex-10 65349984 18.50 ns/op 432.34 MB/s 0 B/op 0 allocs/op
BenchmarkCounterLoad/Atomic-10 1000000000 0.5131 ns/op 15590.98 MB/s 0 B/op 0 allocs/op
BenchmarkCounterLoad/Mutex-10 87413383 13.72 ns/op 583.05 MB/s 0 B/op 0 allocs/op
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment