Skip to content

Instantly share code, notes, and snippets.

@yyforyongyu
Created January 19, 2023 10:57
Show Gist options
  • Save yyforyongyu/faeceab3de32e208cbe83b9486f5b3cd to your computer and use it in GitHub Desktop.
Save yyforyongyu/faeceab3de32e208cbe83b9486f5b3cd to your computer and use it in GitHub Desktop.
Benchmark on read and write for `atomic.Bool` and mutex `bool`
func BenchmarkBoolAmoticWrite(b *testing.B) {
type foo struct {
x atomic.Bool
}
f := &foo{}
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
f.x.Store(true)
}
})
}
func BenchmarkBoolRWMutexWrite(b *testing.B) {
type foo struct {
x bool
mu sync.RWMutex
}
f := &foo{}
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
f.mu.Lock()
f.x = true
f.mu.Unlock()
}
})
}
func BenchmarkBoolAmoticRead(b *testing.B) {
type foo struct {
x atomic.Bool
}
f := &foo{}
f.x.Store(true)
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
_ = f.x.Load()
}
})
}
func BenchmarkBoolRWMutexRead(b *testing.B) {
type foo struct {
x bool
mu sync.RWMutex
}
f := &foo{x: true}
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
f.mu.Lock()
_ = f.x
f.mu.Unlock()
}
})
}
@yyforyongyu
Copy link
Author

BenchmarkBoolAmoticWrite-10     	490353902	         2.234 ns/op
BenchmarkBoolRWMutexWrite-10    	 9906782	       119.9 ns/op
BenchmarkBoolAmoticRead-10      	1000000000	         0.1124 ns/op
BenchmarkBoolRWMutexRead-10     	 9924812	       121.8 ns/op

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment