Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of doing bitwise operations on bitsets

Tags:

c++

bitset

In C++ if I do a logical OR (or AND) on two bitsets, for example:

bitset<1000000> b1, b2;
//some stuff
b1 |= b2;

Does this happen in O(n) or O(1) time? Why?

Also, can this be accomplished using an array of bools in O(1) time?

Thanks.

like image 831
citizenCode Avatar asked Mar 05 '12 04:03

citizenCode


People also ask

Are Bitsets fast?

As bitset stores the same information in compressed manner the operation on bitset are faster than that of array and vector.

How fast is bitwise operations?

Bitwise operations are incredibly simple and thus usually faster than arithmetic operations. For example to get the green portion of an rgb value, the arithmetic approach is (rgb / 256) % 256 . With bitwise operations you would do something as (rgb >> 8) & 0xFF .

Is std :: Bitset efficient?

Rhetorical question: Why std::bitset is written in that inefficacy way? Answer: It is not. If i > 64 then bit set will be zero and in case of unsigned we have UB.

Why are bitwise operations faster?

Yes, Bitwise operations are alot faster than any arithmetic operations because these operations are performed directly on the bits that is 0 and 1. In this operation we will get the output Odd.


1 Answers

It has to happen in O(N) time since there is a finite number of bits that can be processed in any given chunk of time by a given processor platform. In other words, the larger the bit-set, the longer the amount of time each operation will take, and the increase will be linear with respect to the number of bits in the bitset.

You also end up with the same problem using the array of bool types. While each individual operation itself will take O(1) time, the total amount of time for N objects will be O(N).

like image 131
Jason Avatar answered Oct 09 '22 18:10

Jason