github.com/alphadose/zenq/v2@v2.8.4/benchmarks/selector/main.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "time" 6 7 "github.com/alphadose/zenq/v2" 8 ) 9 10 type custom1 struct { 11 alpha int 12 beta string 13 } 14 15 type custom2 struct { 16 gamma int 17 } 18 19 const ( 20 bufferSize = 8 21 22 numProducers = 4 23 ) 24 25 var ( 26 throughput int 27 28 // input batch size 29 testcases = []int{60, 600, 6e3, 6e5} 30 31 zq1 = zenq.New[int](bufferSize) 32 zq2 = zenq.New[string](bufferSize) 33 zq3 = zenq.New[custom1](bufferSize) 34 zq4 = zenq.New[*custom2](bufferSize) 35 36 ch1 = make(chan int, bufferSize) 37 ch2 = make(chan string, bufferSize) 38 ch3 = make(chan custom1, bufferSize) 39 ch4 = make(chan *custom2, bufferSize) 40 ) 41 42 func zenqSelector() { 43 go looper(intProducer1) 44 go looper(stringProducer1) 45 go looper(custom1Producer1) 46 go looper(custom2Producer1) 47 48 var ctr = 0 49 50 var startTime time.Time = time.Now() 51 for i := 0; i < throughput; i++ { 52 if d := zenq.Select(zq1, zq2, zq3, zq4); d != nil { 53 ctr++ 54 } 55 } 56 57 if ctr != throughput { 58 panic("Data Loss") 59 } 60 fmt.Printf("ZenQ Select Runner completed transfer in: %v\n", time.Since(startTime)) 61 } 62 63 func chanSelector() { 64 go looper(intProducer2) 65 go looper(stringProducer2) 66 go looper(custom1Producer2) 67 go looper(custom2Producer2) 68 69 var ctr = 0 70 71 var startTime time.Time = time.Now() 72 for i := 0; i < throughput; i++ { 73 select { 74 case <-ch1: 75 ctr++ 76 case <-ch2: 77 ctr++ 78 case <-ch3: 79 ctr++ 80 case <-ch4: 81 ctr++ 82 } 83 84 } 85 86 if ctr != throughput { 87 panic("Data Loss") 88 } 89 fmt.Printf("Chan Select Runner completed transfer in: %v\n", time.Since(startTime)) 90 } 91 92 func main() { 93 for _, tput := range testcases { 94 throughput = tput 95 fmt.Printf("With Input Batch Size: %d and Num Concurrent Writers: %d\n", throughput, numProducers) 96 fmt.Print("\n") 97 98 // Run tests 99 chanSelector() 100 zenqSelector() 101 fmt.Print("====================================================================\n\n") 102 } 103 } 104 105 func intProducer1(ctr int) { zq1.Write(ctr) } 106 107 func stringProducer1(ctr int) { zq2.Write(fmt.Sprint(ctr * 10)) } 108 109 func custom1Producer1(ctr int) { zq3.Write(custom1{alpha: ctr, beta: fmt.Sprint(ctr)}) } 110 111 func custom2Producer1(ctr int) { zq4.Write(&custom2{gamma: 1 << ctr}) } 112 113 func intProducer2(ctr int) { ch1 <- ctr } 114 115 func stringProducer2(ctr int) { ch2 <- fmt.Sprint(ctr * 10) } 116 117 func custom1Producer2(ctr int) { ch3 <- custom1{alpha: ctr, beta: fmt.Sprint(ctr)} } 118 119 func custom2Producer2(ctr int) { ch4 <- &custom2{gamma: 1 << ctr} } 120 121 func looper(producer func(ctr int)) { 122 for i := 0; i < throughput/numProducers; i++ { 123 producer(i) 124 } 125 }