forked from RoaringBitmap/roaring
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ctz_test.go
113 lines (98 loc) · 2 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
110
111
112
113
package roaring
import (
"encoding/binary"
"math/rand"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestCountTrailingZeros072(t *testing.T) {
Convey("countTrailingZeros", t, func() {
So(numberOfTrailingZeros(0), ShouldEqual, 64)
So(numberOfTrailingZeros(8), ShouldEqual, 3)
So(numberOfTrailingZeros(7), ShouldEqual, 0)
So(numberOfTrailingZeros(1<<17), ShouldEqual, 17)
So(numberOfTrailingZeros(7<<17), ShouldEqual, 17)
So(numberOfTrailingZeros(255<<33), ShouldEqual, 33)
So(countTrailingZeros(0), ShouldEqual, 64)
So(countTrailingZeros(8), ShouldEqual, 3)
So(countTrailingZeros(7), ShouldEqual, 0)
So(countTrailingZeros(1<<17), ShouldEqual, 17)
So(countTrailingZeros(7<<17), ShouldEqual, 17)
So(countTrailingZeros(255<<33), ShouldEqual, 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))
}