使用位集代替手写位操作代码?
在手写的地方使用位集是否有任何性能损失/增益?
如何在运行时使用位集构建以下内容,
- 使 2 到 5 之间的所有位均为零,即
11110011
。
Is there any performance loss/gain using bitset in place where hand written?
How to build the following using a bitset at runtime
- make all the bits between 2 and 5 as zero i.e.,
11110011
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
黄金法则:
不要过早优化!
在 99% 的情况下,Bitset 会足够快,并且具有作为通用概念的优势,因此它更可读性强,并且不易出现实现错误。不要简单地假设您的代码显然需要提高速度;使用 bitset 编写代码,分析您的应用程序,并查看是否:
根据 80-20 规则,如果使其他一些代码更快,您很可能会获得更大的回报。嘿,如果事实证明您确实需要提高位旋转速度,那么至少您有一些不错的基线数据可以使用,以表明您的解决方案确实比默认解决方案更快(无论如何您都需要它)如果您想优化性能)。
The golden rule:
Don't optimise prematurely!
Bitset will in 99% of cases, be fast enough, and has the advantage of being a common concept such that it's both more readable, and less prone to implementation errors. Don't simply assume that your code will obviously need the speed increase; write the code using bitset, profile your application, and see if:
Per the 80-20 rule, chances are that you'll get a much greater return on making some other bit of code faster. And hey, if it turns out that you do need to improve the bit-twiddling speed, at least you have some decent baseline figures to use in order to show that you r solution really is faster than the default (which you'd need anyway if you wanted to optimise for performance).
第二个问题的最简单的解决方案是使用另一个位集。
在给定两个位位置的情况下,需要进行一些数学运算才能得出
mask
的表达式。[编辑]
好的,这是数学。诀窍在于
(1UL << X) -1
是X
的序列。例如 3 => 00000111。因此,(1<<5)-(1<<3)=00011111-00000111-1+1=00011000(位3和4)。因此在代码中:
The easiest solution to your second question would be to use another bitset.
It takes a bit of math to come up with an expression for
mask
given two bit positions.[edit]
Ok, here's the math. The trick is that
(1UL << X) -1
is a sequence ofX
ones. E.g. 3 => 00000111.Hence, (1<<5) - (1<<3) = 00011111 - 00000111 -1 + 1 = 00011000 (bits 3 and 4). Thus in code:
对于上面这样的简单示例,一个不错的手动编码解决方案将比使用 bitset 更快,但两种情况下的性能差异都会很小。
For a simple example such as the above, a decent hand-coded solution will be faster than using bitset, but the performance differences in either case would be small.