Skip to content

Instantly share code, notes, and snippets.

@dim
Created February 28, 2017 16:49
Show Gist options
  • Save dim/152e6bf80e1384ea72e17ac717a5000a to your computer and use it in GitHub Desktop.
Save dim/152e6bf80e1384ea72e17ac717a5000a to your computer and use it in GitHub Desktop.
Benchmark: sync.RWMutex vs atomic.Value
/*
Benchmark_RWMutex-4 100000000 18.1 ns/op
Benchmark_Atomic-4 200000000 8.01 ns/op
Benchmark_RWMutex_parallel-4 30000000 46.7 ns/op
Benchmark_Atomic_parallel-4 1000000000 2.61 ns/op
*/
package main
import (
"sync"
"sync/atomic"
"testing"
)
func Benchmark_RWMutex(b *testing.B) {
var lock sync.RWMutex
m := map[int]int{1: 2}
for i := 0; i < b.N; i++ {
lock.RLock()
_ = m[1]
lock.RUnlock()
}
}
func Benchmark_Atomic(b *testing.B) {
var ptr atomic.Value
ptr.Store(map[int]int{1: 2})
for i := 0; i < b.N; i++ {
m := ptr.Load().(map[int]int)
_ = m[1]
}
}
func Benchmark_RWMutex_parallel(b *testing.B) {
var lock sync.RWMutex
m := map[int]int{1: 2}
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
lock.RLock()
_ = m[1]
lock.RUnlock()
}
})
}
func Benchmark_Atomic_parallel(b *testing.B) {
var ptr atomic.Value
ptr.Store(map[int]int{1: 2})
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
m := ptr.Load().(map[int]int)
_ = m[1]
}
})
}
@abergasov
Copy link

abergasov commented May 19, 2021

atomic/mutex offen use in concurrent
if change test to goroutine in loop - situation changing

BenchmarkLockMultiply
BenchmarkLockMultiply-8     	 5213317	       232.3 ns/op
BenchmarkAtomicMultiply
BenchmarkAtomicMultiply-8   	 5166256	       230.2 ns/op
BenchmarkLockOne
BenchmarkLockOne-8          	104955392	        11.45 ns/op
BenchmarkAtomicOne
BenchmarkAtomicOne-8        	249697118	         4.790 ns/op

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