Peng Yan
Practice Go: Testing
Task: create basic test case and benchmark test with go
bitcount_test.go
func TestLookup(t *testing.T) {
var tests = []struct {
testInt uint64
result int
}{
{1213164123131294294, 30},
{65, 2},
{16, 1},
{11, 3},
}
for _, testcase := range tests {
if ok := LookupImprove(testcase.testInt); ok != testcase.result {
t.Errorf("Return wrong result (%b), expect %d but got %d", testcase.testInt, testcase.result, ok)
}
}
}
var test uint64
func BenchmarkLookup(b *testing.B) {
for i := 0; i < b.N; i++ {
Lookup(test)
}
}
func BenchmarkLookupImprove(b *testing.B) {
for i := 0; i < b.N; i++ {
LookupImprove(test)
}
}
func BenchmarkAll(b *testing.B) {
seed := time.Now().UTC().UnixNano()
random := rand.New(rand.NewSource(seed))
test = uint64(random.Int63())
b.Run("lookup", BenchmarkLookup)
b.Run("lookupImprove", BenchmarkLookupImprove)
}
bitcount.go
var table [256]byte
func init() {
for i := range table {
table[i] = table[i/2] + byte(i&1)
}
}
func Lookup(v uint64) (sum int) {
for i := 0; i < 8; i++ {
sum += int(table[byte(v>>uint(i*8))])
}
return
}
func LookupImprove(v uint64) (sum int) {
if v == 0 {
return sum
}
sum = 1
for v&(v-1) != 0 {
v = v & (v - 1)
sum++
}
return
}