v8.run/go/exp@v0.0.26-0.20230226010534-afcdbd3f782d/pool2/gopool2/gopool2_test.go (about)

     1  package gopool2_test
     2  
     3  import (
     4  	"sync"
     5  	"testing"
     6  	"time"
     7  
     8  	"v8.run/go/exp/pool2/gopool2"
     9  )
    10  
    11  func some_io_job(wg *sync.WaitGroup) {
    12  	time.Sleep(time.Millisecond * 50)
    13  	wg.Done()
    14  }
    15  
    16  func BenchmarkGoPool2(b *testing.B) {
    17  	p := gopool2.New()
    18  	var wg sync.WaitGroup
    19  	wg.Add(b.N)
    20  
    21  	b.ResetTimer()
    22  	for i := 0; i < b.N; i++ {
    23  		p.Do(func() {
    24  			some_io_job(&wg)
    25  		})
    26  	}
    27  	wg.Wait()
    28  }
    29  
    30  func BenchmarkGo(b *testing.B) {
    31  	var wg sync.WaitGroup
    32  	wg.Add(b.N)
    33  
    34  	b.ResetTimer()
    35  	for i := 0; i < b.N; i++ {
    36  		go func() {
    37  			some_io_job(&wg)
    38  		}()
    39  	}
    40  	wg.Wait()
    41  }
    42  
    43  type SimpleGo struct {
    44  	job chan func()
    45  }
    46  
    47  var simplePool sync.Pool
    48  
    49  func init() {
    50  	simplePool = sync.Pool{
    51  		New: func() interface{} {
    52  			g := &SimpleGo{
    53  				job: make(chan func()),
    54  			}
    55  			go func() {
    56  				for j := range g.job {
    57  					j()
    58  					simplePool.Put(g)
    59  				}
    60  			}()
    61  			return g
    62  		},
    63  	}
    64  }
    65  
    66  func BenchmarkSimpleGo(b *testing.B) {
    67  	var wg sync.WaitGroup
    68  	wg.Add(b.N)
    69  
    70  	b.ResetTimer()
    71  	for i := 0; i < b.N; i++ {
    72  		g := simplePool.Get().(*SimpleGo)
    73  		g.job <- func() {
    74  			some_io_job(&wg)
    75  		}
    76  	}
    77  	wg.Wait()
    78  }