开发者

Using bitset in place of using hand written bit manipulation code?

开发者 https://www.devze.com 2023-01-07 02:56 出处:网络
Is there any performance loss/gain开发者_运维问答 using bitset in place where hand written? How to build the following using a bitset at runtime

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.


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:

  1. It's fast enough as it is; and
  2. If it's not fast enough, does it really spend the majority of its time doing bit operations?

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).


The easiest solution to your second question would be to use another bitset.

void makebitszero(bitset<8>& b) {
  // Everything but bits 3 and 4 (between 2 and 5).
  static const bitset<8> mask = ~bitset<8>(12);
  b &= mask;
}

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 of X ones. E.g. 3 => 00000111. Hence, (1<<5) - (1<<3) = 00011111 - 00000111 -1 + 1 = 00011000 (bits 3 and 4). Thus in code:

template<int i, int j, int N> 
void makeBitsZero(bitset<N>& b) {
  // Everything from bit i up to but not including bit j (i < j)
  static const bitset<N> mask = ~bitset<N>(1UL<<j) - (1UL<<i));
  b &= mask;
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号