syncAtomicMutexBench_test
Go Playground
Last update, on 2015, Tue 17 Nov, 18:25:01
/* ... <== see fragment description ... */ package main import ( "sync" "sync/atomic" "testing" ) type Config struct { sync.RWMutex endpoint string } func BenchmarkPMutexSet(b *testing.B) { config := Config{} b.ReportAllocs() b.RunParallel(func(pb *testing.PB) { for pb.Next() { config.Lock() config.endpoint = "gofragments.net" config.Unlock() } }) } func BenchmarkPAtomicSet(b *testing.B) { var config atomic.Value c := Config{endpoint: "gofragments.net"} b.ReportAllocs() b.RunParallel(func(pb *testing.PB) { for pb.Next() { config.Store(c) } }) } func BenchmarkPMutexGet(b *testing.B) { config := Config{endpoint: "gofragments.net"} b.ReportAllocs() b.RunParallel(func(pb *testing.PB) { for pb.Next() { config.RLock() _ = config.endpoint config.RUnlock() } }) } func BenchmarkPAtomicGet(b *testing.B) { var config atomic.Value config.Store(Config{endpoint: "gofragments.net"}) b.ReportAllocs() b.RunParallel(func(pb *testing.PB) { for pb.Next() { _ = config.Load().(Config) } }) } /* Expected Output: from your terminal, invoke: 'go test -bench=.' # with version go1.5.1 amd64 BenchmarkPMutexSet-4 20000000 73.0 ns/op 0 B/op 0 allocs/op BenchmarkPAtomicSet-4 20000000 79.0 ns/op 48 B/op 1 allocs/op BenchmarkPMutexGet-4 30000000 49.2 ns/op 0 B/op 0 allocs/op BenchmarkPAtomicGet-4 200000000 6.27 ns/op 0 B/op 0 allocs/op # with version go.1.4.2 amd64 BenchmarkPMutexSet 20000000 112 ns/op 0 B/op 0 allocs/op BenchmarkPAtomicSet 5000000 299 ns/op 48 B/op 1 allocs/op BenchmarkPMutexGet 30000000 48.9 ns/op 0 B/op 0 allocs/op BenchmarkPAtomicGet 30000000 50.1 ns/op 0 B/op 0 allocs/op */