github.com/xmidt-org/webpa-common@v1.11.9/semaphore/benchmarks_test.go (about)

     1  package semaphore
     2  
     3  import (
     4  	"sync"
     5  	"sync/atomic"
     6  	"testing"
     7  )
     8  
     9  func benchmarkAtomic(b *testing.B) {
    10  	var value int32
    11  
    12  	b.RunParallel(func(pb *testing.PB) {
    13  		for pb.Next() {
    14  			atomic.AddInt32(&value, 1)
    15  		}
    16  	})
    17  }
    18  
    19  func benchmarkSyncMutex(b *testing.B) {
    20  	var (
    21  		value int
    22  		lock  sync.Mutex
    23  	)
    24  
    25  	b.RunParallel(func(pb *testing.PB) {
    26  		for pb.Next() {
    27  			lock.Lock()
    28  			value++
    29  			lock.Unlock()
    30  		}
    31  	})
    32  }
    33  
    34  func benchmarkBinarySemaphore(b *testing.B) {
    35  	var (
    36  		value int
    37  		m     = Mutex()
    38  	)
    39  
    40  	b.ResetTimer()
    41  	b.RunParallel(func(pb *testing.PB) {
    42  		for pb.Next() {
    43  			m.Acquire()
    44  			value++
    45  			m.Release()
    46  		}
    47  	})
    48  }
    49  
    50  func benchmarkCloseableBinarySemaphore(b *testing.B) {
    51  	var (
    52  		value int
    53  		m     = CloseableMutex()
    54  	)
    55  
    56  	b.ResetTimer()
    57  	b.RunParallel(func(pb *testing.PB) {
    58  		for pb.Next() {
    59  			m.Acquire()
    60  			value++
    61  			m.Release()
    62  		}
    63  	})
    64  }
    65  
    66  func benchmarkChannel(b *testing.B) {
    67  	var (
    68  		value   int
    69  		updates = make(chan chan struct{}, 1)
    70  	)
    71  
    72  	go func() {
    73  		for u := range updates {
    74  			value++
    75  			close(u)
    76  		}
    77  	}()
    78  
    79  	defer close(updates)
    80  	b.ResetTimer()
    81  	b.RunParallel(func(pb *testing.PB) {
    82  		for pb.Next() {
    83  			result := make(chan struct{})
    84  			updates <- result
    85  			<-result
    86  		}
    87  	})
    88  }
    89  
    90  func BenchmarkSingleResource(b *testing.B) {
    91  	b.Run("atomic", benchmarkAtomic)
    92  	b.Run("sync.Mutex", benchmarkSyncMutex)
    93  	b.Run("semaphore", func(b *testing.B) {
    94  		b.Run("binary", benchmarkBinarySemaphore)
    95  		b.Run("closeable", benchmarkCloseableBinarySemaphore)
    96  	})
    97  	b.Run("channel", benchmarkChannel)
    98  }