github.com/reusee/pr2@v0.0.0-20230630035947-72a20ff5e864/bench_test.go (about)

     1  package pr2
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"sync"
     7  	"testing"
     8  )
     9  
    10  func BenchmarkConsume(b *testing.B) {
    11  
    12  	for i := 1; i < 16; i *= 2 {
    13  		b.Run(fmt.Sprintf("%d", i), func(b *testing.B) {
    14  
    15  			put, wait := Consume(context.Background(), i, func(i int, v any) error {
    16  				return nil
    17  			})
    18  			b.ResetTimer()
    19  
    20  			for i := 0; i < b.N; i++ {
    21  				put(i)
    22  			}
    23  			if err := wait(true); err != nil {
    24  				b.Fatal(err)
    25  			}
    26  
    27  		})
    28  	}
    29  
    30  }
    31  
    32  func BenchmarkBaseline(b *testing.B) {
    33  	for i := 1; i < 16; i *= 2 {
    34  		b.Run(fmt.Sprintf("%d", i), func(b *testing.B) {
    35  
    36  			wg := new(sync.WaitGroup)
    37  			wg.Add(i)
    38  			ch := make(chan int)
    39  			for range make([]struct{}, i) {
    40  				go func() {
    41  					defer wg.Done()
    42  					for range ch {
    43  					}
    44  				}()
    45  			}
    46  			b.ResetTimer()
    47  
    48  			for i := 0; i < b.N; i++ {
    49  				ch <- i
    50  			}
    51  			close(ch)
    52  			wg.Wait()
    53  
    54  		})
    55  	}
    56  
    57  }