Skip to content

Instantly share code, notes, and snippets.

@kisielk
Created December 1, 2013 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kisielk/7730157 to your computer and use it in GitHub Desktop.
Save kisielk/7730157 to your computer and use it in GitHub Desktop.
package mutexbench
import (
"runtime"
"sync"
"testing"
)
func BenchmarkMutex100(b *testing.B) { benchMutex(b, 1000) }
func BenchmarkMutex1000(b *testing.B) { benchMutex(b, 1000) }
func BenchmarkMutex10000(b *testing.B) { benchMutex(b, 10000) }
func BenchmarkMutex100000(b *testing.B) { benchMutex(b, 100000) }
func benchMutex(b *testing.B, n int) {
for i := 0; i < b.N; i++ {
var m sync.Mutex
var wg sync.WaitGroup
for g := 0; g < runtime.GOMAXPROCS(0)+1; g++ {
wg.Add(1)
go func() {
m.Lock()
for j := 0; j < n; j++ {
}
m.Unlock()
wg.Done()
}()
}
wg.Wait()
}
}
func BenchmarkRWMutex100(b *testing.B) { benchRWMutex(b, 1000) }
func BenchmarkRWMutex1000(b *testing.B) { benchRWMutex(b, 1000) }
func BenchmarkRWMutex10000(b *testing.B) { benchRWMutex(b, 10000) }
func BenchmarkRWMutex100000(b *testing.B) { benchRWMutex(b, 100000) }
func benchRWMutex(b *testing.B, n int) {
for i := 0; i < b.N; i++ {
var m sync.RWMutex
var wg sync.WaitGroup
for g := 0; g < runtime.GOMAXPROCS(0)+1; g++ {
wg.Add(1)
go func() {
m.Lock()
for j := 0; j < n; j++ {
}
m.Unlock()
wg.Done()
}()
}
wg.Wait()
}
}
func BenchmarkRWMutexRlock100(b *testing.B) { benchRWMutexRlock(b, 100) }
func BenchmarkRWMutexRlock1000(b *testing.B) { benchRWMutexRlock(b, 1000) }
func BenchmarkRWMutexRlock10000(b *testing.B) { benchRWMutexRlock(b, 10000) }
func BenchmarkRWMutexRlock100000(b *testing.B) { benchRWMutexRlock(b, 100000) }
func benchRWMutexRlock(b *testing.B, n int) {
for i := 0; i < b.N; i++ {
var m sync.RWMutex
var wg sync.WaitGroup
for g := 0; g < runtime.GOMAXPROCS(0)+1; g++ {
wg.Add(1)
go func() {
m.RLock()
for j := 0; j < n; j++ {
}
m.RUnlock()
wg.Done()
}()
}
wg.Wait()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment