Merge pull request #104968 from twpayne/twpayne/ones-count-64

Speed up counting of bits in allocator
This commit is contained in:
Kubernetes Prow Robot 2021-10-01 19:27:05 -07:00 committed by GitHub
commit 0ac956ff2b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 2 deletions

View File

@ -24,8 +24,8 @@ import (
// countBits returns the number of set bits in n // countBits returns the number of set bits in n
func countBits(n *big.Int) int { func countBits(n *big.Int) int {
var count int = 0 var count int = 0
for _, b := range n.Bytes() { for _, w := range n.Bits() {
count += bits.OnesCount8(uint8(b)) count += bits.OnesCount64(uint64(w))
} }
return count return count
} }

View File

@ -22,12 +22,18 @@ import (
) )
func TestCountBits(t *testing.T) { func TestCountBits(t *testing.T) {
// bigN is an integer that occupies more than one big.Word.
bigN, ok := big.NewInt(0).SetString("10000000000000000000000000000000000000000000000000000000000000000", 16)
if !ok {
t.Fatal("Failed to set bigN")
}
tests := []struct { tests := []struct {
n *big.Int n *big.Int
expected int expected int
}{ }{
{n: big.NewInt(int64(0)), expected: 0}, {n: big.NewInt(int64(0)), expected: 0},
{n: big.NewInt(int64(0xffffffffff)), expected: 40}, {n: big.NewInt(int64(0xffffffffff)), expected: 40},
{n: bigN, expected: 1},
} }
for _, test := range tests { for _, test := range tests {
actual := countBits(test.n) actual := countBits(test.n)
@ -36,3 +42,13 @@ func TestCountBits(t *testing.T) {
} }
} }
} }
func BenchmarkCountBits(b *testing.B) {
bigN, ok := big.NewInt(0).SetString("10000000000000000000000000000000000000000000000000000000000000000", 16)
if !ok {
b.Fatal("Failed to set bigN")
}
for i := 0; i < b.N; i++ {
countBits(bigN)
}
}