mirror of
https://github.com/HDT3213/godis.git
synced 2025-10-07 17:51:10 +08:00
optimize randomLevel
This commit is contained in:
@@ -1,6 +1,9 @@
|
|||||||
package sortedset
|
package sortedset
|
||||||
|
|
||||||
import "math/rand"
|
import (
|
||||||
|
"math/bits"
|
||||||
|
"math/rand"
|
||||||
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
maxLevel = 16
|
maxLevel = 16
|
||||||
@@ -53,14 +56,9 @@ func makeSkiplist() *skiplist {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func randomLevel() int16 {
|
func randomLevel() int16 {
|
||||||
level := int16(1)
|
total := uint64(1)<<uint64(maxLevel) - 1
|
||||||
for float32(rand.Int31()&0xFFFF) < (0.25 * 0xFFFF) {
|
k := rand.Uint64() % total
|
||||||
level++
|
return maxLevel - int16(bits.Len64(k)) + 1
|
||||||
}
|
|
||||||
if level < maxLevel {
|
|
||||||
return level
|
|
||||||
}
|
|
||||||
return maxLevel
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (skiplist *skiplist) insert(member string, score float64) *node {
|
func (skiplist *skiplist) insert(member string, score float64) *node {
|
||||||
|
14
datastruct/sortedset/skiplist_test.go
Normal file
14
datastruct/sortedset/skiplist_test.go
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
package sortedset
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestRandomLevel(t *testing.T) {
|
||||||
|
m := make(map[int16]int)
|
||||||
|
for i := 0; i < 10000; i++ {
|
||||||
|
level := randomLevel()
|
||||||
|
m[level]++
|
||||||
|
}
|
||||||
|
for i := 0; i <= maxLevel; i++ {
|
||||||
|
t.Logf("level %d, count %d", i, m[int16(i)])
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user