poll_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. package gopool
  15. import (
  16. "runtime"
  17. "sync"
  18. "sync/atomic"
  19. "testing"
  20. )
  21. const benchmarkTimes = 10000
  22. func DoCopyStack(a, b int) int {
  23. if b < 100 {
  24. return DoCopyStack(0, b+1)
  25. }
  26. return 0
  27. }
  28. func testFunc() {
  29. DoCopyStack(0, 0)
  30. }
  31. func testPanicFunc() {
  32. panic("test")
  33. }
  34. func TestPool(t *testing.T) {
  35. p := NewPool("test", 100, NewConfig())
  36. var n int32
  37. var wg sync.WaitGroup
  38. for i := 0; i < 2000; i++ {
  39. wg.Add(1)
  40. p.Go(func() {
  41. defer wg.Done()
  42. atomic.AddInt32(&n, 1)
  43. })
  44. }
  45. wg.Wait()
  46. if n != 2000 {
  47. t.Error(n)
  48. }
  49. }
  50. func TestPoolPanic(t *testing.T) {
  51. p := NewPool("test", 100, NewConfig())
  52. p.Go(testPanicFunc)
  53. }
  54. func BenchmarkPool(b *testing.B) {
  55. config := NewConfig()
  56. config.ScaleThreshold = 1
  57. p := NewPool("benchmark", int32(runtime.GOMAXPROCS(0)), config)
  58. var wg sync.WaitGroup
  59. b.ReportAllocs()
  60. b.ResetTimer()
  61. for i := 0; i < b.N; i++ {
  62. wg.Add(benchmarkTimes)
  63. for j := 0; j < benchmarkTimes; j++ {
  64. p.Go(func() {
  65. testFunc()
  66. wg.Done()
  67. })
  68. }
  69. wg.Wait()
  70. }
  71. }
  72. func BenchmarkGo(b *testing.B) {
  73. var wg sync.WaitGroup
  74. b.ReportAllocs()
  75. b.ResetTimer()
  76. for i := 0; i < b.N; i++ {
  77. wg.Add(benchmarkTimes)
  78. for j := 0; j < benchmarkTimes; j++ {
  79. go func() {
  80. testFunc()
  81. wg.Done()
  82. }()
  83. }
  84. wg.Wait()
  85. }
  86. }