Skip to content

Instantly share code, notes, and snippets.

@woodsaj
Created September 19, 2018 07:40
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 woodsaj/ffb18944042ed34e57a5ca38464195d7 to your computer and use it in GitHub Desktop.
Save woodsaj/ffb18944042ed34e57a5ca38464195d7 to your computer and use it in GitHub Desktop.
Benchmark to compare shared locks vs per-thread locks
package input
import (
"fmt"
"sync"
"testing"
)
// simple datastruct to provide a lock around an int variable
type Data struct {
sync.RWMutex
D int
}
func (d *Data) Get() int {
d.RLock()
defer d.RUnlock()
return d.D
}
func doWork(pb *testing.PB, d *Data) {
for pb.Next() {
if d.Get() > 1 {
fmt.Printf("data is > 1")
}
}
}
func BenchmarkSharedLock(b *testing.B) {
b.SetParallelism(8)
d := &Data{}
b.RunParallel(func(pb *testing.PB) {
doWork(pb, d)
})
}
func BenchmarkIsolatedLock(b *testing.B) {
b.SetParallelism(8)
b.RunParallel(func(pb *testing.PB) {
d := &Data{}
doWork(pb, d)
})
}
@woodsaj
Copy link
Author

woodsaj commented Sep 19, 2018

anthony:~/go/src/github.com/grafana/metrictank/input$ go test -v -run NONE -bench Lock -cpu=1,2,4
goos: linux
goarch: amd64
pkg: github.com/grafana/metrictank/input
BenchmarkSharedLock             30000000                54.6 ns/op
BenchmarkSharedLock-2           20000000                70.6 ns/op
BenchmarkSharedLock-4           20000000                68.7 ns/op
BenchmarkThreadLock             30000000                56.6 ns/op
BenchmarkThreadLock-2           50000000                27.6 ns/op
BenchmarkThreadLock-4           100000000               14.6 ns/op
PASS
ok      github.com/grafana/metrictank/input     9.283s

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