Skip to content

Instantly share code, notes, and snippets.

@miku
Created January 5, 2017 00:01
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 miku/c4b66c7e1c8aa9c9b9cb3baa022411ca to your computer and use it in GitHub Desktop.
Save miku/c4b66c7e1c8aa9c9b9cb3baa022411ca to your computer and use it in GitHub Desktop.
Popcount, Hamming, POPCNT, Population count, Golang, https://play.golang.org/p/M2nxXCyrd7
package main
import (
"fmt"
"testing"
"time"
)
const N = 8
var a [1 << N]byte
func init() {
for i := range a {
var n byte
for x := i; x != 0; x >>= 1 {
if x&1 != 0 {
n++
}
}
a[i] = n
}
}
func popcount(x uint64) (n byte) {
return a[byte(x>>0*N)] +
a[byte(x>>1*N)] +
a[byte(x>>2*N)] +
a[byte(x>>3*N)] +
a[byte(x>>4*N)] +
a[byte(x>>5*N)] +
a[byte(x>>6*N)] +
a[byte(x>>7*N)]
}
func BenchmarkPopcount(b *testing.B) {
x := uint64(0x73fa55623a30abed)
for i := b.N; i > 0; i-- {
popcount(x)
}
}
func main() {
res := testing.Benchmark(BenchmarkPopcount)
fmt.Println(res.N, res.T, time.Duration(int64(res.T)/int64(res.N)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment