Skip to content

Instantly share code, notes, and snippets.

@veggiemonk
Created November 10, 2024 13:08
Show Gist options
  • Save veggiemonk/0b2cc987a4d5914b3885bbaad0340601 to your computer and use it in GitHub Desktop.
Save veggiemonk/0b2cc987a4d5914b3885bbaad0340601 to your computer and use it in GitHub Desktop.
quick benchmark for atomic
package main
import (
"sync"
"sync/atomic"
"testing"
)
type atom struct {
value atomic.Int64
}
type mute struct {
value int64
lock sync.Mutex
}
var (
a = atom{}
m = mute{}
)
var (
resa int64 = 0
resm int64 = 0
)
func BenchmarkAtomicWrite(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
a.value.Add(1)
}
})
}
func BenchmarkMutexWrite(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
m.lock.Lock()
m.value++
m.lock.Unlock()
}
})
}
func BenchmarkAtomicRead(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
var r int64
for pb.Next() {
r = a.value.Load()
}
resa = r
})
}
func BenchmarkMutexRead(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
var r int64
for pb.Next() {
m.lock.Lock()
r = m.value
m.lock.Unlock()
}
resm = r
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment