forked from torbiak/gopl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
popcount_test.go
66 lines (56 loc) · 1.13 KB
/
popcount_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
// ex2.4: compare popcount implementations, including looping table lookups and
// shift value.
package popcount
import (
"testing"
)
func PopCountTableLoop(x uint64) int {
sum := 0
for i := 0; i < 8; i++ {
sum += int(pc[byte(x>>uint(i))])
}
return sum
}
func PopCountShiftValue(x uint64) int {
count := 0
mask := uint64(1)
for i := 0; i < 64; i++ {
if x&mask > 0 {
count++
}
x >>= 1
}
return count
}
// pc[i] is the population count of i.
var pc [256]byte
func init() {
for i := range pc {
pc[i] = pc[i/2] + byte(i&1)
}
}
// PopCount returns the population count (number of set bits) of x.
func PopCountTable(x uint64) int {
return int(pc[byte(x>>(0*8))] +
pc[byte(x>>(1*8))] +
pc[byte(x>>(2*8))] +
pc[byte(x>>(3*8))] +
pc[byte(x>>(4*8))] +
pc[byte(x>>(5*8))] +
pc[byte(x>>(6*8))] +
pc[byte(x>>(7*8))])
}
func bench(b *testing.B, f func(uint64) int) {
for i := 0; i < b.N; i++ {
f(uint64(i))
}
}
func BenchmarkTable(b *testing.B) {
bench(b, PopCountTable)
}
func BenchmarkTableLoop(b *testing.B) {
bench(b, PopCountTableLoop)
}
func BenchmarkShiftValue(b *testing.B) {
bench(b, PopCountShiftValue)
}