github.com/bytedance/gopkg@v0.0.0-20240514070511-01b2cbcf35e1/cloud/circuitbreaker/counter_test.go (about) 1 // Copyright 2021 ByteDance Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package circuitbreaker 16 17 import ( 18 "sync" 19 "testing" 20 ) 21 22 func BenchmarkAtomicCounter_Add(b *testing.B) { 23 c := atomicCounter{} 24 b.SetParallelism(1000) 25 b.RunParallel(func(p *testing.PB) { 26 for p.Next() { 27 c.Add(1) 28 } 29 }) 30 } 31 32 func BenchmarkPerPCounter_Add(b *testing.B) { 33 c := newPerPCounter() 34 b.SetParallelism(1000) 35 b.RunParallel(func(p *testing.PB) { 36 for p.Next() { 37 c.Add(1) 38 } 39 }) 40 } 41 42 func TestPerPCounter(t *testing.T) { 43 numPerG := 1000 44 numG := 1000 45 c := newPerPCounter() 46 c1 := atomicCounter{} 47 var wg sync.WaitGroup 48 wg.Add(numG) 49 for i := 0; i < numG; i++ { 50 go func() { 51 defer wg.Done() 52 for i := 0; i < numPerG; i++ { 53 c.Add(1) 54 c1.Add(1) 55 } 56 }() 57 } 58 wg.Wait() 59 total := c.Get() 60 total1 := c1.Get() 61 if total != c1.Get() { 62 t.Errorf("expected %d, get %d", total1, total) 63 } 64 c.Zero() 65 c1.Zero() 66 if c.Get() != 0 || c1.Get() != 0 { 67 t.Errorf("zero failed") 68 } 69 }