Created
May 14, 2018 13:40
-
-
Save toVersus/ed124b4fc7ac1f4ee6156b62510fb488 to your computer and use it in GitHub Desktop.
Benchmark tips#1: https://github.com/golang/go/issues/14813
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Author
toVersus
commented
May 14, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment