github.com/bytedance/gopkg@v0.0.0-20240514070511-01b2cbcf35e1/util/gopool/pool_test.go (about)

     1  // Copyright 2021 ByteDance Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package gopool
    16  
    17  import (
    18  	"runtime"
    19  	"sync"
    20  	"sync/atomic"
    21  	"testing"
    22  )
    23  
    24  const benchmarkTimes = 10000
    25  
    26  func DoCopyStack(a, b int) int {
    27  	if b < 100 {
    28  		return DoCopyStack(0, b+1)
    29  	}
    30  	return 0
    31  }
    32  
    33  func testFunc() {
    34  	DoCopyStack(0, 0)
    35  }
    36  
    37  func testPanicFunc() {
    38  	panic("test")
    39  }
    40  
    41  func TestPool(t *testing.T) {
    42  	p := NewPool("test", 100, NewConfig())
    43  	var n int32
    44  	var wg sync.WaitGroup
    45  	for i := 0; i < 2000; i++ {
    46  		wg.Add(1)
    47  		p.Go(func() {
    48  			defer wg.Done()
    49  			atomic.AddInt32(&n, 1)
    50  		})
    51  	}
    52  	wg.Wait()
    53  	if n != 2000 {
    54  		t.Error(n)
    55  	}
    56  }
    57  
    58  func TestPoolPanic(t *testing.T) {
    59  	p := NewPool("test", 100, NewConfig())
    60  	p.Go(testPanicFunc)
    61  }
    62  
    63  func BenchmarkPool(b *testing.B) {
    64  	config := NewConfig()
    65  	config.ScaleThreshold = 1
    66  	p := NewPool("benchmark", int32(runtime.GOMAXPROCS(0)), config)
    67  	var wg sync.WaitGroup
    68  	b.ReportAllocs()
    69  	b.ResetTimer()
    70  	for i := 0; i < b.N; i++ {
    71  		wg.Add(benchmarkTimes)
    72  		for j := 0; j < benchmarkTimes; j++ {
    73  			p.Go(func() {
    74  				testFunc()
    75  				wg.Done()
    76  			})
    77  		}
    78  		wg.Wait()
    79  	}
    80  }
    81  
    82  func BenchmarkGo(b *testing.B) {
    83  	var wg sync.WaitGroup
    84  	b.ReportAllocs()
    85  	b.ResetTimer()
    86  	for i := 0; i < b.N; i++ {
    87  		wg.Add(benchmarkTimes)
    88  		for j := 0; j < benchmarkTimes; j++ {
    89  			go func() {
    90  				testFunc()
    91  				wg.Done()
    92  			}()
    93  		}
    94  		wg.Wait()
    95  	}
    96  }