funcPopCount2(x uint64)int { ret := 0 for i := 0; i < 64; i++ { if x&1 == 1 { ret += 1 } x = x >> 1 } return ret }
funcBenchmarkPopCount2(b *testing.B) { // 20000000 60.5 ns/op // >> 循环 for i := 0; i < b.N; i++ { PopCount2(2<<63 - 1) } }
练习2.5
使用x&(x-1)可以清除x最右边的非零位,利用该特点写一个PopCount,然后评价它的性能
x&(x-1)面试基础题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
funcPopCount3(x uint64)int { ret := 0 for x != 0 { x = (x - 1) & x ret += 1 } return ret } funcBenchmarkPopCount3(b *testing.B) { // 30000000 50.5 ns/op // x&(x-1) for i := 0; i < b.N; i++ { PopCount3(2<<63 - 1) } }