github.com/coyove/sdss@v0.0.0-20231129015646-c2ec58cca6a2/future/clock_test.go (about) 1 package future 2 3 import ( 4 "fmt" 5 "math/rand" 6 "sync" 7 "sync/atomic" 8 "testing" 9 "time" 10 ) 11 12 func TestNow(t *testing.T) { 13 StartWatcher(func(e error) { 14 fmt.Println(e) 15 }) 16 17 dedup := map[Future]bool{} 18 mu := sync.Mutex{} 19 20 for i := 0; i < 20; i++ { 21 wg := sync.WaitGroup{} 22 var tot int64 23 const N = 5000 24 for i := 0; i < N; i++ { 25 wg.Add(1) 26 go func() { 27 start := UnixNano() 28 ts := Get(1) // int64(rand.Intn(Channels))) 29 // fmt.Println(ts.Channel(), ts.IsFixed(), ts.Fixed(), Future(ts.Fixed()).IsFixed()) 30 v := uint16(rand.Int()) 31 v0, _ := ts.ToCookie(v).Cookie() 32 if v0 != v { 33 panic("invalid cookie") 34 } 35 36 mu.Lock() 37 if dedup[ts] { 38 panic("duplicated id") 39 } 40 dedup[ts] = true 41 mu.Unlock() 42 43 ts.Wait() 44 diff := UnixNano() - start 45 atomic.AddInt64(&tot, diff) 46 wg.Done() 47 }() 48 } 49 wg.Wait() 50 fmt.Println(tot / N / 1e6) 51 } 52 } 53 54 func TestFuzzyID(t *testing.T) { 55 const N = 500 56 rand.Seed(UnixNano()) 57 m := sync.Map{} 58 test = true 59 for i := 0; i < 5; i++ { 60 wg := sync.WaitGroup{} 61 for j := 0; j < N/5; j++ { 62 wg.Add(1) 63 go func(i int) { 64 defer wg.Done() 65 id := Get(1) 66 _, loaded := m.LoadOrStore(id, 1) 67 if loaded { 68 panic("duplicated id") 69 } 70 time.Sleep(time.Duration(rand.Intn(1000)+500) * time.Millisecond) 71 }(i*100 + j) 72 } 73 wg.Wait() 74 } 75 }