Skip to content

Instantly share code, notes, and snippets.

@toVersus
Created May 14, 2018 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toVersus/ed124b4fc7ac1f4ee6156b62510fb488 to your computer and use it in GitHub Desktop.
Save toVersus/ed124b4fc7ac1f4ee6156b62510fb488 to your computer and use it in GitHub Desktop.
package main
// Hamming weight algorithm
// https://en.wikipedia.org/wiki/Hamming_weight
const m1 = 0x5555555555555555
const m2 = 0x3333333333333333
const m4 = 0x0f0f0f0f0f0f0f0f
const h01 = 0x0101010101010101
func main() {
popcnt(112)
}
func popcnt(x uint64) int {
x -= (x >> 1) & m1
x = (x & m2) + ((x >> 2) & m2)
x = (x + (x >> 4)) & m4
return int((x * h01) >> 56)
}
package main
import "testing"
func BenchmarkBadPopcnt(b *testing.B) {
for i := 0; i < b.N; i++ {
popcnt(uint64(i))
}
}
var result int
func BenchmarkPopcnt(b *testing.B) {
var n int
for i := 0; i < b.N; i++ {
n = popcnt(uint64(i))
}
result = n
}
@toVersus
Copy link
Author

PS> go test -bench . --benchmem
goos: windows
goarch: amd64
pkg: github.com/toversus/ssa-optimize
BenchmarkBadPopcnt-8    2000000000               0.25 ns/op            0 B/op          0 allocs/op
BenchmarkPopcnt-8       1000000000               2.01 ns/op            0 B/op          0 allocs/op
PASS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment