Created
February 28, 2017 16:49
-
-
Save dim/152e6bf80e1384ea72e17ac717a5000a to your computer and use it in GitHub Desktop.
Benchmark: sync.RWMutex vs atomic.Value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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] | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
atomic/mutex offen use in concurrent
if change test to goroutine in loop - situation changing