Skip to content

Commit

Permalink
[dbnode] Use bits.LeadingZeros64 to improve encoder performance (#2857)
Browse files Browse the repository at this point in the history
Co-authored-by: Rob Skillington <[email protected]>
  • Loading branch information
linasm and robskillington authored Nov 9, 2020
1 parent 4071759 commit 48f781f
Show file tree
Hide file tree
Showing 3 changed files with 113 additions and 14 deletions.
19 changes: 5 additions & 14 deletions src/dbnode/encoding/encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,25 +22,16 @@ package encoding

import "math/bits"

// Bit is just a byte
// Bit is just a byte.
type Bit byte

// NumSig returns the number of significant values in a uint64
// NumSig returns the number of significant bits in a uint64.
func NumSig(v uint64) uint8 {
if v == 0 {
return 0
}

numLeading := uint8(0)
for tmp := v; (tmp & (1 << 63)) == 0; tmp <<= 1 {
numLeading++
}

return uint8(64) - numLeading
return uint8(64 - bits.LeadingZeros64(v))
}

// LeadingAndTrailingZeros calculates the number of leading and trailing 0s
// for a uint64
// for a uint64.
func LeadingAndTrailingZeros(v uint64) (int, int) {
if v == 0 {
return 64, 0
Expand All @@ -51,7 +42,7 @@ func LeadingAndTrailingZeros(v uint64) (int, int) {
return numLeading, numTrailing
}

// SignExtend sign extends the highest bit of v which has numBits (<=64)
// SignExtend sign extends the highest bit of v which has numBits (<=64).
func SignExtend(v uint64, numBits uint) int64 {
shift := 64 - numBits
return (int64(v) << shift) >> shift
Expand Down
6 changes: 6 additions & 0 deletions src/dbnode/encoding/encoding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,17 @@
package encoding

import (
"math"
"testing"

"github.com/stretchr/testify/require"
)

func TestNumSig(t *testing.T) {
require.Equal(t, uint8(0), NumSig(uint64(0)))
require.Equal(t, uint8(1), NumSig(uint64(1)))
require.Equal(t, uint8(4), NumSig(uint64(12)))
require.Equal(t, uint8(63), NumSig(uint64(math.MaxUint64>>1)))
require.Equal(t, uint8(64), NumSig(uint64(math.MaxUint64)))
require.Equal(t, uint8(64), NumSig(uint64(math.MaxUint64-1)))
}
Loading

0 comments on commit 48f781f

Please sign in to comment.