SHARE
TWEET

Untitled

a guest Jul 24th, 2019 60 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package bench
  2.  
  3. import (
  4.     "sync"
  5.     "sync/atomic"
  6.     "testing"
  7. )
  8.  
  9. func BenchmarkWithNoBuffer(b *testing.B) {
  10.     benchmarkWithBuffer(b, 0)
  11. }
  12.  
  13. func BenchmarkWithBufferSizeOf1(b *testing.B) {
  14.     benchmarkWithBuffer(b, 1)
  15. }
  16.  
  17. func BenchmarkWithBufferSizeEqualsToNumberOfWorker(b *testing.B) {
  18.     benchmarkWithBuffer(b, 5)
  19. }
  20.  
  21. func BenchmarkWithBufferSizeExceedsNumberOfWorker(b *testing.B) {
  22.     benchmarkWithBuffer(b, 25)
  23. }
  24.  
  25. func benchmarkWithBuffer(b *testing.B, size int) {
  26.     for i := 0; i < b.N; i++ {
  27.         c := make(chan uint32, size)
  28.  
  29.         var wg sync.WaitGroup
  30.         wg.Add(1)
  31.  
  32.         go func() {
  33.             defer wg.Done()
  34.  
  35.             for i := uint32(0); i < 1000; i++ {
  36.                 c <- i%2
  37.             }
  38.             close(c)
  39.         }()
  40.  
  41.         var total uint32
  42.         for w := 0; w < 5; w++ {
  43.             wg.Add(1)
  44.             go func() {
  45.                 defer wg.Done()
  46.  
  47.                 for {
  48.                     v, ok := <-c
  49.                     if !ok {
  50.                         break
  51.                     }
  52.                     atomic.AddUint32(&total, v)
  53.                 }
  54.             }()
  55.         }
  56.  
  57.         wg.Wait()
  58.     }
  59. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top