Created
April 11, 2015 01:05
-
-
Save phemmer/6e4264defa8547ce8646 to your computer and use it in GitHub Desktop.
golang locking benchmarks
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
package main | |
import ( | |
"sync" | |
"sync/atomic" | |
"testing" | |
) | |
var v int64 | |
var mutex sync.Mutex | |
func BenchmarkMutex(b *testing.B) { | |
v = 0 | |
for i := 0; i < b.N; i++ { | |
mutex.Lock() | |
v++ | |
mutex.Unlock() | |
} | |
} | |
var rwMutex sync.RWMutex | |
func BenchmarkRWMutex_lock(b *testing.B) { | |
v = 0 | |
for i := 0; i < b.N; i++ { | |
rwMutex.Lock() | |
v++ | |
rwMutex.Unlock() | |
} | |
} | |
func BenchmarkRWMutex_rLock(b *testing.B) { | |
v = 0 | |
for i := 0; i < b.N; i++ { | |
rwMutex.RLock() | |
v++ | |
rwMutex.RUnlock() | |
} | |
} | |
func BenchmarkAtomicAdd(b *testing.B) { | |
v = 0 | |
for i := 0; i < b.N; i++ { | |
atomic.AddInt64(&v, 1) | |
} | |
} |
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
# go test -v -bench=. | |
testing: warning: no tests to run | |
PASS | |
BenchmarkMutex 50000000 28.0 ns/op | |
BenchmarkRWMutex_lock 30000000 57.0 ns/op | |
BenchmarkRWMutex_rLock 50000000 28.0 ns/op | |
BenchmarkAtomicAdd 100000000 14.0 ns/op | |
ok tmp/c1v 6.037s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment