-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex03_false_sharing_bench_test.go
More file actions
64 lines (54 loc) · 1.25 KB
/
ex03_false_sharing_bench_test.go
File metadata and controls
64 lines (54 loc) · 1.25 KB
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
package memorymodel
import (
"sync"
"sync/atomic"
"testing"
)
// Run with: `go test -bench BenchmarkFalseSharing`
func BenchmarkFalseSharing(b *testing.B) {
b.Run("Naive (Shared Cache Line)", func(b *testing.B) {
m := &NaiveMetrics{}
var wg sync.WaitGroup
b.ResetTimer()
for i := 0; i < b.N; i++ {
wg.Add(2)
// Both coroutines slam the exact same memory cache line structure simultaneously
go func() {
defer wg.Done()
for j := 0; j < 10_000; j++ {
atomic.AddInt64(&m.Counter1, 1) // Core 1
}
}()
go func() {
defer wg.Done()
for j := 0; j < 10_000; j++ {
atomic.AddInt64(&m.Counter2, 1) // Core 2
}
}()
wg.Wait()
}
})
b.Run("Padded (Independent Cache Lines)", func(b *testing.B) {
m := &PaddedMetrics{}
var wg sync.WaitGroup
b.ResetTimer()
for i := 0; i < b.N; i++ {
wg.Add(2)
go func() {
defer wg.Done()
for j := 0; j < 10_000; j++ {
atomic.AddInt64(&m.Counter1, 1)
}
}()
go func() {
defer wg.Done()
for j := 0; j < 10_000; j++ {
atomic.AddInt64(&m.Counter2, 1)
}
}()
wg.Wait()
}
})
// When the student fixes `PaddedMetrics`, the second benchmark will run
// significantly faster (often 2x-4x faster on modern multi-core CPUs).
}