Skip to content

Commit

Permalink
math/bits: faster Reverse8/16 functions using table lookups
Browse files Browse the repository at this point in the history
Measured on 2.3 GHz Intel Core i7, running macOS 10.12.3:

benchmark                old ns/op     new ns/op     delta
BenchmarkReverse8-8      1.70          0.99          -41.76%
BenchmarkReverse16-8     2.24          1.32          -41.07%

Fixes #19279.

Change-Id: I398cf8a3513b7fa63c130efc7846a7c5353999d4
Reviewed-on: https://go-review.googlesource.com/37459
Run-TryBot: Robert Griesemer <gri@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
  • Loading branch information
griesemer committed Feb 25, 2017
1 parent bf584b1 commit e18adbf
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 9 deletions.
13 changes: 4 additions & 9 deletions src/math/bits/bits.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:generate go run make_tables.go

// Package bits implements bit counting and manipulation
// functions for the predeclared unsigned integer types.
package bits
Expand Down Expand Up @@ -232,19 +234,12 @@ func Reverse(x uint) uint {

// Reverse8 returns the value of x with its bits in reversed order.
func Reverse8(x uint8) uint8 {
const m = 1<<8 - 1
x = x>>1&(m0&m) | x&(m0&m)<<1
x = x>>2&(m1&m) | x&(m1&m)<<2
return x>>4 | x<<4
return rev8tab[x]
}

// Reverse16 returns the value of x with its bits in reversed order.
func Reverse16(x uint16) uint16 {
const m = 1<<16 - 1
x = x>>1&(m0&m) | x&(m0&m)<<1
x = x>>2&(m1&m) | x&(m1&m)<<2
x = x>>4&(m2&m) | x&(m2&m)<<4
return x>>8 | x<<8
return uint16(rev8tab[x>>8]) | uint16(rev8tab[x&0xff])<<8
}

// Reverse32 returns the value of x with its bits in reversed order.
Expand Down
26 changes: 26 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.

66 changes: 66 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 e18adbf

Please sign in to comment.