-
Notifications
You must be signed in to change notification settings - Fork 0
/
ms15LenIdGen_test.go
63 lines (57 loc) · 1.32 KB
/
ms15LenIdGen_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
package heldiamgo
import (
"runtime"
"sync"
"sync/atomic"
"testing"
"fmt"
"github.com/smartystreets/goconvey/convey"
)
func TestNewMs15LenIDGenerator(t *testing.T) {
runtime.GOMAXPROCS(runtime.NumCPU()) //多核计算
lock := &sync.RWMutex{}
m := map[int64]int64{}
count := int64(0)
w := &sync.WaitGroup{}
convey.Convey("ID生成器", t, func() {
for a := 0; a < 32; a++ {
w.Add(10)
go func(a int) {
idWorker := NewMs15LenIDGenerator(int64(a))
for j := 0; j < 10; j++ { //每个生成器10个协程同时生成id
go func(idWorker *Ms15LenIDGenerator) {
var id int64
for i := 0; i < 10000; i++ {
id, _ = idWorker.NextID()
lock.Lock()
if _, ok := m[id]; ok {
atomic.AddInt64(&count, 1)
} else {
m[id] = id
}
lock.Unlock()
}
w.Done()
}(idWorker)
}
}(a)
}
w.Wait()
fmt.Printf("一共生成[%d]个,重复数[%d]", len(m), count)
convey.So(count, convey.ShouldEqual, 0)
})
}
func BenchmarkMs15LenIDGenerator_NextString(b *testing.B) {
idWorker := NewMs15LenIDGenerator(10)
for i := 0; i < b.N; i++ {
idWorker.NextID()
}
}
func BenchmarkMs15LenIDGenerator_NextIdRunParallel(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
idWorker := NewMs15LenIDGenerator(1)
for pb.Next() {
idWorker.NextID()
}
})
}