-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpool_bench_test.go
107 lines (90 loc) · 1.67 KB
/
pool_bench_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package bees
import (
"context"
"runtime"
"sync"
"testing"
"time"
)
const (
_ = 1 << (10 * iota)
_
MiB
)
const (
poolSize = 500000
sleep = 10
benchRunTimes = 10000000
)
// memory usage: 1034 MB
func BenchmarkSemaphore(b *testing.B) {
runtime.GOMAXPROCS(2)
var wg sync.WaitGroup
sema := make(chan struct{}, poolSize)
b.StartTimer()
for i := 0; i < b.N; i++ {
wg.Add(benchRunTimes)
for j := 0; j < benchRunTimes; j++ {
sema <- struct{}{}
go func() {
demoFunc()
<-sema
wg.Done()
}()
}
}
wg.Wait()
b.StopTimer()
b.Logf("memory usage:%d MB", checkMem())
}
// memory usage: 963 MB
func BenchmarkGoroutines(b *testing.B) {
runtime.GOMAXPROCS(2)
var wg sync.WaitGroup
b.StartTimer()
for i := 0; i < b.N; i++ {
wg.Add(benchRunTimes)
for j := 0; j < benchRunTimes; j++ {
go func() {
demoFunc()
wg.Done()
}()
}
}
wg.Wait()
b.StopTimer()
b.Logf("memory usage:%d MB", checkMem())
}
// memory usage: 27 MB
func BenchmarkWorkerPool(b *testing.B) {
runtime.GOMAXPROCS(2)
var wg sync.WaitGroup
p := Create(context.Background(), WithCapacity(poolSize), WithKeepAlive(5*time.Second))
defer func() {
p.Close()
}()
task := func(ctx context.Context) {
defer wg.Done()
demoFunc()
}
b.StartTimer()
for i := 0; i < b.N; i++ {
wg.Add(benchRunTimes)
for j := 0; j < benchRunTimes; j++ {
p.Submit(task)
}
}
wg.Wait()
b.StopTimer()
b.Logf("memory usage:%d MB", checkMem())
}
func checkMem() uint64 {
var curMem uint64
mem := runtime.MemStats{}
runtime.ReadMemStats(&mem)
curMem = mem.TotalAlloc/MiB - curMem
return curMem
}
func demoFunc() {
time.Sleep(time.Duration(sleep) * time.Millisecond)
}