github.com/pharosnet/flyline@v1.0.2/array_buffer_benchmark_test.go (about) 1 package flyline 2 3 import ( 4 "context" 5 "runtime" 6 "testing" 7 ) 8 9 func BenchmarkArrayBufferOneGoroutine(b *testing.B) { 10 runtime.GOMAXPROCS(1) 11 defer runtime.GOMAXPROCS(1) 12 benchmarkArrayBuffer(b, 1) 13 } 14 15 func BenchmarkArrayBufferTwoGoroutines(b *testing.B) { 16 runtime.GOMAXPROCS(2) 17 defer runtime.GOMAXPROCS(1) 18 benchmarkArrayBuffer(b, 1) 19 } 20 func BenchmarkArrayBufferThreeGoroutinesWithContendedWrite(b *testing.B) { 21 runtime.GOMAXPROCS(3) 22 defer runtime.GOMAXPROCS(1) 23 benchmarkArrayBuffer(b, 2) 24 } 25 26 func benchmarkArrayBuffer(b *testing.B, writers int64) { 27 iterations := int64(b.N) 28 maxReads := iterations * writers 29 30 buf := NewArrayBuffer(1024 * 16) 31 b.ReportAllocs() 32 b.ResetTimer() 33 for x := int64(0); x < writers; x++ { 34 go func() { 35 for i := int64(0); i < iterations; { 36 buf.Send(i) 37 i++ 38 } 39 }() 40 } 41 buf.Close() 42 43 for i := int64(0); i < maxReads; i++ { 44 buf.Recv() 45 } 46 b.StopTimer() 47 48 buf.Sync(context.Background()) 49 50 } 51 52 func BenchmarkNonBlockingOneGoroutine(b *testing.B) { 53 runtime.GOMAXPROCS(1) 54 defer runtime.GOMAXPROCS(1) 55 benchmarkNonBlocking(b, 1) 56 } 57 58 func BenchmarkNonBlockingTwoGoroutines(b *testing.B) { 59 runtime.GOMAXPROCS(2) 60 defer runtime.GOMAXPROCS(1) 61 benchmarkNonBlocking(b, 1) 62 } 63 func BenchmarkNonBlockingThreeGoroutinesWithContendedWrite(b *testing.B) { 64 runtime.GOMAXPROCS(3) 65 defer runtime.GOMAXPROCS(1) 66 benchmarkNonBlocking(b, 2) 67 } 68 69 func benchmarkNonBlocking(b *testing.B, writers int64) { 70 iterations := int64(b.N) 71 maxReads := iterations * writers 72 channel := make(chan int64, 1024*16) 73 74 b.ReportAllocs() 75 b.ResetTimer() 76 77 for x := int64(0); x < writers; x++ { 78 go func() { 79 for i := int64(0); i < iterations; { 80 select { 81 case channel <- i: 82 i++ 83 default: 84 continue 85 } 86 } 87 }() 88 } 89 90 for i := int64(0); i < maxReads; i++ { 91 <-channel 92 } 93 94 b.StopTimer() 95 96 close(channel) 97 }