github.com/maypok86/otter@v1.2.1/internal/queue/queue_bench_test.go (about) 1 // Copyright (c) 2024 Alexey Mayshev. All rights reserved. 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 queue 16 17 import ( 18 "runtime" 19 "sync/atomic" 20 "testing" 21 ) 22 23 func benchmarkProdCons(b *testing.B, push func(int), pop func() int, queueSize, localWork int) { 24 b.Helper() 25 26 callsPerSched := queueSize 27 procs := runtime.GOMAXPROCS(-1) / 2 28 if procs == 0 { 29 procs = 1 30 } 31 N := int32(b.N / callsPerSched) 32 c := make(chan bool, 2*procs) 33 for p := 0; p < procs; p++ { 34 go func() { 35 foo := 0 36 for atomic.AddInt32(&N, -1) >= 0 { 37 for g := 0; g < callsPerSched; g++ { 38 for i := 0; i < localWork; i++ { 39 foo *= 2 40 foo /= 2 41 } 42 push(1) 43 } 44 } 45 push(0) 46 c <- foo == 42 47 }() 48 go func() { 49 foo := 0 50 for { 51 v := pop() 52 if v == 0 { 53 break 54 } 55 for i := 0; i < localWork; i++ { 56 foo *= 2 57 foo /= 2 58 } 59 } 60 c <- foo == 42 61 }() 62 } 63 for p := 0; p < procs; p++ { 64 <-c 65 <-c 66 } 67 } 68 69 func BenchmarkGrowableProdConsWork100(b *testing.B) { 70 length := 128 * 16 71 g := NewGrowable[int](uint32(length), uint32(length)) 72 b.ResetTimer() 73 benchmarkProdCons(b, func(i int) { 74 g.Push(i) 75 }, func() int { 76 return g.Pop() 77 }, length, 100) 78 } 79 80 func BenchmarkChanProdConsWork100(b *testing.B) { 81 length := 128 * 16 82 c := make(chan int, length) 83 benchmarkProdCons(b, func(i int) { 84 c <- i 85 }, func() int { 86 return <-c 87 }, length, 100) 88 }