Skip to content

Instantly share code, notes, and snippets.

@phemmer
Created April 11, 2015 01:05
Show Gist options
  • Save phemmer/6e4264defa8547ce8646 to your computer and use it in GitHub Desktop.
Save phemmer/6e4264defa8547ce8646 to your computer and use it in GitHub Desktop.
golang locking benchmarks
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)
}
}
# 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