generated from atomicgo/template
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcounter_test.go
94 lines (77 loc) · 1.72 KB
/
counter_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
package counter
import (
"sync"
"testing"
"github.com/MarvinJWendt/testza"
)
func TestCounter(t *testing.T) {
var c *Counter
t.Run("Start", func(t *testing.T) {
c = NewCounter().Start()
})
t.Run("Increment 10 times", func(t *testing.T) {
for i := 0; i < 10; i++ {
c.Increment()
}
testza.AssertEqual(t, uint64(10), c.Count())
})
t.Run("Increment another 10 times", func(t *testing.T) {
for i := 0; i < 10; i++ {
c.Increment()
}
testza.AssertEqual(t, uint64(20), c.Count())
})
t.Run("Reset counter", func(t *testing.T) {
c.Reset()
testza.AssertEqual(t, uint64(0), c.Count())
})
t.Run("Start timer again", func(t *testing.T) {
c.Start()
})
t.Run("Increment 1_000_000 times", func(t *testing.T) {
for i := 0; i < 1_000_000; i++ {
c.Increment()
}
testza.AssertEqual(t, uint64(1_000_000), c.Count())
})
t.Run("Stop", func(t *testing.T) {
c.Stop()
})
}
// basicCounter is a basic implementation of a counter.
// It's used to compare the performance to our version.
type basicCounter struct {
mutex sync.Mutex
count uint64
}
func (c *basicCounter) Increment() {
c.mutex.Lock()
defer c.mutex.Unlock()
c.count++
}
func (c *basicCounter) Count() uint64 {
c.mutex.Lock()
defer c.mutex.Unlock()
return c.count
}
func BenchmarkBasicCounterImplementation(b *testing.B) {
counter := basicCounter{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
counter.Increment()
}
}
func BenchmarkIncrement(b *testing.B) {
counter := NewCounter().Start()
b.ResetTimer()
for i := 0; i < b.N; i++ {
counter.Increment()
}
}
func BenchmarkIncrementWithAdvancedStats(b *testing.B) {
counter := NewCounter().WithAdvancedStats().Start()
b.ResetTimer()
for i := 0; i < b.N; i++ {
counter.Increment()
}
}