Skip to content
/ popcnt Public

Improve popcnt performance by using simd instructions

License

Notifications You must be signed in to change notification settings

Orlion/popcnt

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

popcnt

Improve popcnt performance by using simd instructions.

使用SIMD指令提升popcnt性能。

Desc

对于一个int64数字来说可以直接使用bits.OnesCount64或者popcnt指令来获取其bit位为1的数量,但如果对于一个[...]int64这样的数组(比如bitmap)来说只能遍历这个数组挨个计算最后取和,性能比较差。

我们可以利用SIMD指令并行同时计算多个int64数字的bit位为1的个数,理论上可以提高N倍性能。

Benchmark

# go test -bench=. -v
=== RUN   TestSimdPopcntQuad
--- PASS: TestSimdPopcntQuad (0.00s)
goos: linux
goarch: amd64
pkg: github.com/Orlion/popcnt
cpu: Intel Core Processor (Broadwell, no TSX)
BenchmarkSimdPopcntQuad
BenchmarkSimdPopcntQuad-8        3693530               330.8 ns/op
BenchmarkSerial
BenchmarkSerial-8               539924296                2.232 ns/op
PASS
ok      github.com/Orlion/popcnt        2.993s

可以看到使用SIMD指令优化之后性能下降了约150倍,与预期严重不符。

进一步优化思路

  1. popcnt.s中汇编代码中可以看到逻辑较为啰嗦,还有优化空间。
  2. 对于一个int64切片仍然要循环调用SimdPopcntQuad函数来计算,SimdPopcntQuad函数中又有许多寄存器初始化的代码,这样大量时间浪费寄存器初始化的工作上,可以改造下SimdPopcntQuad函数,使其接收一个int64切片,在一个汇编函数中直接计算出结果。

About

Improve popcnt performance by using simd instructions

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages