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
108
109
110
111
112
113
114
115
116
117
118
119
120
|
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package syncs_test
import (
"expvar"
"sync"
"testing"
. "tailscale.com/syncs"
"tailscale.com/tstest"
)
var (
_ expvar.Var = (*ShardedInt)(nil)
// TODO(raggi): future go version:
// _ encoding.TextAppender = (*ShardedInt)(nil)
)
func BenchmarkShardedInt(b *testing.B) {
b.ReportAllocs()
b.Run("expvar", func(b *testing.B) {
var m expvar.Int
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
m.Add(1)
}
})
})
b.Run("sharded-int", func(b *testing.B) {
m := NewShardedInt()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
m.Add(1)
}
})
})
}
func TestShardedInt(t *testing.T) {
t.Run("basics", func(t *testing.T) {
m := NewShardedInt()
if got, want := m.Value(), int64(0); got != want {
t.Errorf("got %v, want %v", got, want)
}
m.Add(1)
if got, want := m.Value(), int64(1); got != want {
t.Errorf("got %v, want %v", got, want)
}
m.Add(2)
if got, want := m.Value(), int64(3); got != want {
t.Errorf("got %v, want %v", got, want)
}
m.Add(-1)
if got, want := m.Value(), int64(2); got != want {
t.Errorf("got %v, want %v", got, want)
}
})
t.Run("high-concurrency", func(t *testing.T) {
m := NewShardedInt()
wg := sync.WaitGroup{}
numWorkers := 1000
numIncrements := 1000
wg.Add(numWorkers)
for range numWorkers {
go func() {
defer wg.Done()
for range numIncrements {
m.Add(1)
}
}()
}
wg.Wait()
if got, want := m.Value(), int64(numWorkers*numIncrements); got != want {
t.Errorf("got %v, want %v", got, want)
}
for i, shard := range m.GetDistribution() {
t.Logf("shard %d: %d", i, shard)
}
})
t.Run("encoding-TextAppender", func(t *testing.T) {
m := NewShardedInt()
m.Add(1)
b := make([]byte, 0, 10)
b, err := m.AppendText(b)
if err != nil {
t.Fatal(err)
}
if got, want := string(b), "1"; got != want {
t.Errorf("got %v, want %v", got, want)
}
})
t.Run("allocs", func(t *testing.T) {
m := NewShardedInt()
tstest.MinAllocsPerRun(t, 0, func() {
m.Add(1)
_ = m.Value()
})
// TODO(raggi): fix access to expvar's internal append based
// interface, unfortunately it's not currently closed for external
// use, this will alloc when it escapes.
tstest.MinAllocsPerRun(t, 0, func() {
m.Add(1)
_ = m.String()
})
b := make([]byte, 0, 10)
tstest.MinAllocsPerRun(t, 0, func() {
m.Add(1)
m.AppendText(b)
})
})
}
|