github.com/cloudwego/kitex@v0.9.0/pkg/remote/trans/netpollmux/shard_map_test.go (about) 1 /* 2 * Copyright 2021 CloudWeGo Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package netpollmux 18 19 import ( 20 "sync" 21 "sync/atomic" 22 "testing" 23 24 "github.com/cloudwego/kitex/internal/test" 25 ) 26 27 func TestShardMap(t *testing.T) { 28 m := newShardMap(32) 29 var key int32 30 var mod int32 = 1023 31 // check success 32 for i := int32(0); i <= mod; i++ { 33 m.store(i, nil) 34 } 35 // check range 36 var sum int32 37 m.rangeMap(func(seqID int32, msg EventHandler) { 38 sum++ 39 test.Assert(t, msg == nil) 40 test.Assert(t, 0 < seqID && seqID <= mod, seqID) 41 }) 42 test.Assert(t, sum == mod, sum) 43 // check key=0 44 msg, ok := m.load(key) 45 test.Assert(t, msg == nil) 46 test.Assert(t, ok == false) 47 // check key<0 48 msg, ok = m.load(-1) 49 test.Assert(t, msg == nil) 50 test.Assert(t, ok == false) 51 // check key>0 52 for i := int32(1); i <= mod; i++ { 53 key := i 54 // load, load&delete, check 55 msg, ok := m.load(key) 56 test.Assert(t, msg == nil) 57 test.Assert(t, ok == true) 58 59 // store, delete, check 60 m.store(key, nil) 61 m.delete(key) 62 msg, ok = m.load(key) 63 test.Assert(t, msg == nil) 64 test.Assert(t, ok == false) 65 } 66 67 // check nil 68 for i := int32(0); i <= mod; i++ { 69 msg, ok := m.load(key) 70 test.Assert(t, msg == nil) 71 test.Assert(t, ok == false) 72 m.delete(key) 73 } 74 } 75 76 func BenchmarkSyncMap(b *testing.B) { 77 var m sync.Map 78 var key uint32 79 var mod uint32 = 1023 80 for i := uint32(0); i <= mod; i++ { 81 m.Store(i, nil) 82 } 83 84 b.ReportAllocs() 85 b.StartTimer() 86 b.SetParallelism(1024) 87 b.RunParallel(func(pb *testing.PB) { 88 for pb.Next() { 89 key := atomic.AddUint32(&key, 1) & mod 90 m.Store(key, nil) 91 m.Load(key) 92 m.Delete(key) 93 } 94 }) 95 } 96 97 func BenchmarkShardMap(b *testing.B) { 98 m := newShardMap(32) 99 var key int32 100 var mod int32 = 1023 101 for i := int32(0); i <= mod; i++ { 102 m.store(i, nil) 103 } 104 105 b.ReportAllocs() 106 b.StartTimer() 107 b.SetParallelism(1024) 108 b.RunParallel(func(pb *testing.PB) { 109 for pb.Next() { 110 key := atomic.AddInt32(&key, 1) & mod 111 m.store(key, nil) 112 m.load(key) 113 m.delete(key) 114 } 115 }) 116 }