-
Notifications
You must be signed in to change notification settings - Fork 1
/
popcnt_test.go
71 lines (64 loc) · 1.29 KB
/
popcnt_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
package and
import (
"math/bits"
"math/rand/v2"
"testing"
)
func popcntNaive(a []byte) int {
var ret int
for i := range a {
ret += bits.OnesCount8(a[i])
}
return ret
}
func testPopcntAgainstGeneric(t *testing.T, size int) {
a := make([]byte, size)
rng := rand.New(rand.NewPCG(0, 0))
for i := range a {
a[i] = uint8(rng.UintN(256))
}
got := Popcnt(a)
want := popcntGeneric(a)
if got != want {
t.Fatalf("Popcnt produced a different result from popcntGeneric at length %d: %d; want %d", size, got, want)
}
}
func TestPopcntAgainstGeneric(t *testing.T) {
for i := 0; i < 20; i++ {
size := 1 << i
testPopcntAgainstGeneric(t, size)
for j := 0; j < 10; j++ {
testPopcntAgainstGeneric(t, size+rand.IntN(100))
}
}
}
func BenchmarkPopcnt(b *testing.B) {
b.StopTimer()
size := 1000000
a := make([]byte, size)
b.SetBytes(int64(size))
b.StartTimer()
for i := 0; i < b.N; i++ {
_ = Popcnt(a)
}
}
func BenchmarkPopcntGeneric(b *testing.B) {
b.StopTimer()
size := 1000000
a := make([]byte, size)
b.SetBytes(int64(size))
b.StartTimer()
for i := 0; i < b.N; i++ {
_ = popcntGeneric(a)
}
}
func BenchmarkPopcntNaive(b *testing.B) {
b.StopTimer()
size := 1000000
a := make([]byte, size)
b.SetBytes(int64(size))
b.StartTimer()
for i := 0; i < b.N; i++ {
_ = popcntNaive(a)
}
}