forked from RoaringBitmap/roaring
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ctz_test.go
109 lines (96 loc) · 1.94 KB
/
ctz_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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package roaring
import (
"encoding/binary"
"github.com/stretchr/testify/assert"
"math/rand"
"testing"
)
func TestCountTrailingZeros072(t *testing.T) {
assert.Equal(t, 64, numberOfTrailingZeros(0))
assert.Equal(t, 3, numberOfTrailingZeros(8))
assert.Equal(t, 0, numberOfTrailingZeros(7))
assert.Equal(t, 17, numberOfTrailingZeros(1<<17))
assert.Equal(t, 17, numberOfTrailingZeros(7<<17))
assert.Equal(t, 33, numberOfTrailingZeros(255<<33))
assert.Equal(t, 64, countTrailingZeros(0))
assert.Equal(t, 3, countTrailingZeros(8))
assert.Equal(t, 0, countTrailingZeros(7))
assert.Equal(t, 17, countTrailingZeros(1<<17))
assert.Equal(t, 17, countTrailingZeros(7<<17))
assert.Equal(t, 33, countTrailingZeros(255<<33))
}
func getRandomUint64Set(n int) []uint64 {
seed := int64(42)
rand.Seed(seed)
var buf [8]byte
var o []uint64
for i := 0; i < n; i++ {
rand.Read(buf[:])
o = append(o, binary.LittleEndian.Uint64(buf[:]))
}
return o
}
func getAllOneBitUint64Set() []uint64 {
var o []uint64
for i := uint(0); i < 64; i++ {
o = append(o, 1<<i)
}
return o
}
func Benchmark100OrigNumberOfTrailingZeros(b *testing.B) {
b.StopTimer()
r := getRandomUint64Set(64)
r = append(r, getAllOneBitUint64Set()...)
b.ResetTimer()
b.StartTimer()
for i := 0; i < b.N; i++ {
for i := range r {
numberOfTrailingZeros(r[i])
}
}
}
func Benchmark100CountTrailingZeros(b *testing.B) {
b.StopTimer()
r := getRandomUint64Set(64)
r = append(r, getAllOneBitUint64Set()...)
b.ResetTimer()
b.StartTimer()
for i := 0; i < b.N; i++ {
for i := range r {
countTrailingZeros(r[i])
}
}
}
func numberOfTrailingZeros(i uint64) int {
if i == 0 {
return 64
}
x := i
n := int64(63)
y := x << 32
if y != 0 {
n -= 32
x = y
}
y = x << 16
if y != 0 {
n -= 16
x = y
}
y = x << 8
if y != 0 {
n -= 8
x = y
}
y = x << 4
if y != 0 {
n -= 4
x = y
}
y = x << 2
if y != 0 {
n -= 2
x = y
}
return int(n - int64(uint64(x<<1)>>63))
}