github.com/lrweck/accumulator@v0.0.0-20230204043344-6f6538ed8d35/accumulator_test.go (about)

     1  package accumulator
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"testing"
     7  	"time"
     8  )
     9  
    10  func BenchmarkAccumulatorNoDelay(b *testing.B) {
    11  
    12  	ch := make(chan uint, 9000000)
    13  
    14  	feedChan(ch, 9000000, 0)
    15  	close(ch)
    16  
    17  	acc := New(ch, 300, time.Millisecond/500)
    18  
    19  	var total = 0
    20  	calls := make(map[CallOrigin]int, 3)
    21  	b.ReportAllocs()
    22  	b.ResetTimer()
    23  
    24  	acc.Accumulate(context.Background(), func(c CallOrigin, t []uint) {
    25  		total += len(t)
    26  		calls[c]++
    27  	})
    28  
    29  	b.StopTimer()
    30  
    31  	fmt.Println("total", total)
    32  	fmt.Println("calls", calls)
    33  
    34  }
    35  
    36  func BenchmarkAccumulatorDelay(b *testing.B) {
    37  
    38  	ch := make(chan uint, 10000)
    39  
    40  	acc := New(ch, 50, time.Millisecond)
    41  
    42  	var total = 0
    43  	calls := make(map[CallOrigin]int, 3)
    44  
    45  	go func() {
    46  		feedChan(ch, 5000, time.Second)
    47  		close(ch)
    48  	}()
    49  
    50  	b.ReportAllocs()
    51  	b.ResetTimer()
    52  
    53  	acc.Accumulate(context.Background(), func(c CallOrigin, t []uint) {
    54  		total += len(t)
    55  		calls[c]++
    56  	})
    57  
    58  	b.StopTimer()
    59  
    60  	b.Log("total", total)
    61  	b.Log("calls", calls)
    62  
    63  }
    64  
    65  func feedChan(c chan uint, qty uint, during time.Duration) {
    66  
    67  	sleepFor := during / time.Duration(qty)
    68  
    69  	for i := uint(0); i < qty; i++ {
    70  		c <- i
    71  		if during > 0 {
    72  			time.Sleep(sleepFor)
    73  		}
    74  	}
    75  
    76  }