Skip to content

Commit

Permalink
math/bits: faster TrailingZeroes8
Browse files Browse the repository at this point in the history
For sizes > 8, the existing code is faster.

benchmark                     old ns/op     new ns/op     delta
BenchmarkTrailingZeros8-8     1.95          1.29          -33.85%

Measured on 2.3 GHz Intel Core i7 running macOS 10.12.3.

Change-Id: I6f3a33ec633a2c544ec29693c141f2f99335c745
Reviewed-on: https://go-review.googlesource.com/37581
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
  • Loading branch information
griesemer committed Feb 28, 2017
1 parent d7a659b commit 9515cb5
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 9 deletions.
2 changes: 1 addition & 1 deletion src/math/bits/bits.go
Expand Up @@ -34,7 +34,7 @@ func LeadingZeros64(x uint64) int { return 64 - blen(uint64(x)) }
func TrailingZeros(x uint) int { return ntz(x) }

// TrailingZeros8 returns the number of trailing zero bits in x; the result is 8 for x == 0.
func TrailingZeros8(x uint8) int { return ntz8(x) }
func TrailingZeros8(x uint8) int { return int(ntz8tab[x]) }

// TrailingZeros16 returns the number of trailing zero bits in x; the result is 16 for x == 0.
func TrailingZeros16(x uint16) int { return ntz16(x) }
Expand Down
8 changes: 0 additions & 8 deletions src/math/bits/bits_impl.go
Expand Up @@ -23,14 +23,6 @@ var deBruijn32tab = [32]byte{
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9,
}

func ntz8(x uint8) (n int) {
if x == 0 {
return 8
}
// see comment in ntz64
return int(deBruijn32tab[uint32(x&-x)*deBruijn32>>(32-5)])
}

func ntz16(x uint16) (n int) {
if x == 0 {
return 16
Expand Down
19 changes: 19 additions & 0 deletions src/math/bits/bits_tables.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions src/math/bits/make_tables.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 9515cb5

Please sign in to comment.