github.com/GitbookIO/syncgroup@v0.0.0-20200915204659-4f0b2961ab10/mutexes_bench_test.go (about) 1 package syncgroup 2 3 import ( 4 "strconv" 5 "sync" 6 // "time" 7 8 "testing" 9 ) 10 11 func BenchmarkGoLockUnlock(b *testing.B) { 12 rw := sync.RWMutex{} 13 for n := 0; n < b.N; n++ { 14 rw.Lock() 15 rw.Unlock() 16 } 17 } 18 19 func BenchmarkGroupLockUnlock(b *testing.B) { 20 rw := NewMutexGroup() 21 for n := 0; n < b.N; n++ { 22 rw.Lock("a") 23 rw.Unlock("a") 24 } 25 } 26 27 func BenchmarkShardedLockUnlock(b *testing.B) { 28 rw := NewShardedMutexes() 29 lock := rw.Locker("a") 30 for n := 0; n < b.N; n++ { 31 lock.Lock() 32 lock.Unlock() 33 } 34 } 35 36 func BenchmarkReadGoLockUnlock(b *testing.B) { 37 rw := sync.RWMutex{} 38 for n := 0; n < b.N; n++ { 39 rw.RLock() 40 rw.RUnlock() 41 } 42 } 43 44 func BenchmarkReadGroupLockUnlock(b *testing.B) { 45 rw := NewMutexGroup() 46 for n := 0; n < b.N; n++ { 47 rw.RLock("a") 48 rw.RUnlock("a") 49 } 50 } 51 52 func BenchmarkReadShardedLockUnlock(b *testing.B) { 53 rw := NewShardedMutexes() 54 lock := rw.RLocker("a") 55 for n := 0; n < b.N; n++ { 56 lock.RLock() 57 lock.RUnlock() 58 } 59 } 60 61 // BenchmarkParallelGroup 62 // Runs 100 go-routines read locking/unlocing on a single key (at a time)of a group mutex 63 func BenchmarkParallelGroup(b *testing.B) { 64 M := 4096 65 b.SetParallelism(M) 66 67 locks := NewMutexGroup() 68 keys := nkeys(M) 69 70 b.RunParallel(func(pb *testing.PB) { 71 j := 0 72 for pb.Next() { 73 y := j 74 j++ 75 key := keys[y%M] 76 // Lock, sleep 77 locks.Lock(key) 78 //time.Sleep(1 * time.Millisecond) 79 locks.Unlock(key) 80 } 81 }) 82 } 83 84 // BenchmarkParallelSharded 85 // Runs 100 go-routines read locking/unlocing on a single key (at a time) of a Sharded mutex 86 func BenchmarkParallelSharded(b *testing.B) { 87 M := 4096 88 b.SetParallelism(M) 89 90 locks := NewShardedMutexes() 91 keys := nkeys(M) 92 93 b.RunParallel(func(pb *testing.PB) { 94 j := 0 95 for pb.Next() { 96 y := j 97 j++ 98 key := keys[y%M] 99 lock := locks.Locker(key) 100 // Lock, sleep 101 lock.Lock() 102 //time.Sleep(1 * time.Millisecond) 103 lock.Unlock() 104 } 105 }) 106 } 107 108 // BenchmarkParallelSingle 109 // Runs 100 go-routines read locking/unlocing on a single mutex 110 func BenchmarkParallelSingle(b *testing.B) { 111 M := 4096 112 b.SetParallelism(M) 113 114 lock := sync.RWMutex{} 115 keys := nkeys(M) 116 117 b.RunParallel(func(pb *testing.PB) { 118 j := 0 119 for pb.Next() { 120 y := j 121 j++ 122 _ = keys[y%M] 123 // Lock, sleep 124 lock.Lock() 125 //time.Sleep(1 * time.Millisecond) 126 lock.Unlock() 127 } 128 }) 129 } 130 131 func nkeys(n int) []string { 132 strs := make([]string, n) 133 134 for idx, _ := range strs { 135 strs[idx] = strconv.Itoa(idx) 136 } 137 138 return strs 139 }