-
Notifications
You must be signed in to change notification settings - Fork 1
/
bench_test.go
58 lines (52 loc) · 1.04 KB
/
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
package taskgroup_test
import (
"math/rand/v2"
"sync"
"testing"
)
// A very rough benchmark comparing the performance of accumulating values with
// a separate goroutine via a channel, vs. accumulating them directly under a
// lock. The workload here is intentionally minimal, so the benchmark is
// measuring more or less just the overhead.
func BenchmarkChan(b *testing.B) {
ch := make(chan int)
done := make(chan struct{})
var total int
go func() {
defer close(done)
for v := range ch {
total += v
}
}()
b.ResetTimer() // discount the setup time.
var wg sync.WaitGroup
wg.Add(b.N)
for i := 0; i < b.N; i++ {
go func() {
defer wg.Done()
ch <- rand.IntN(1000)
}()
}
wg.Wait()
close(ch)
<-done
}
func BenchmarkLock(b *testing.B) {
var μ sync.Mutex
var total int
report := func(v int) {
μ.Lock()
defer μ.Unlock()
total += v
}
b.ResetTimer() // discount the setup time.
var wg sync.WaitGroup
wg.Add(b.N)
for i := 0; i < b.N; i++ {
go func() {
defer wg.Done()
report(rand.IntN(1000))
}()
}
wg.Wait()
}