-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnowflake_test.go
52 lines (49 loc) · 1.05 KB
/
snowflake_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
package snowflake
import (
"runtime"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestGenerate(t *testing.T) {
workerId := uint16(123)
snowFlake := NewSnowFlake(workerId)
testId := snowFlake.NextId()
t.Log(GetTimestampFromId(testId))
t.Log(GetWorkerIdFromId(testId))
t.Log(GetSequenceFromId(testId))
var checkMap sync.Map
idCount := int64(0)
for i := 0; i < 16; i++ {
go func() {
for {
atomic.AddInt64(&idCount, 1)
id := snowFlake.NextId()
// check duplicate id
_, loaded := checkMap.LoadOrStore(id, true)
if loaded {
t.Errorf("duplicate id:%v", id)
}
}
}()
}
tick := time.After(time.Second)
<-tick
t.Logf("total:%v", atomic.LoadInt64(&idCount))
}
func BenchmarkAtomic(b *testing.B) {
runtime.GOMAXPROCS(runtime.NumCPU())
workerId := uint16(123)
snowFlake := NewSnowFlake(workerId)
idCount := int64(0)
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
atomic.AddInt64(&idCount, 1)
snowFlake.NextId()
}
})
tick := time.After(time.Second)
<-tick
b.Logf("total:%v", atomic.LoadInt64(&idCount))
}