0

I need to make the last 5 bits of the unsigned int become zero(1111_1111 to 1110_0000)

There are two solution

unsigned int number = 0xFFFF;
unsigned int temp_one = number & (~0x1F);
unsigned int temp_two = number >> 5 << 5;

which one is faster?
I write a small program to measure the time
But it is always 0 after optimize

Thanks a lot

4
Contributors
4
Replies
5
Views
5 Years
Discussion Span
Last Post by firstPerson
0

I write a small program to measure the time

Why don't you put the solution in a loop. Loop it some 100000... times, so that your program will give you some number. Do it separately for both solutions.

0

If you run this with any kind of optimization (or even the base level), it will optimize the entire operations away, making it equivalent to number = 0xFFE0; .

You need to make the number change at run-time and you need to do the operation a lot of times too, maybe like so:

unsigned int and_operator(unsigned int number) {
  return number & (~0x1F);
};

unsigned int bit_shifting(unsigned int number) {
  return (number >> 5) << 5;
};

int main() {

  srand((unsigned int)time(NULL));
  
  for(unsigned int i = 0; i < 1000000; ++i)
    unsigned int result = and_operator( rand() );

  for(unsigned int i = 0; i < 1000000; ++i)
    unsigned int result = bit_shifting( rand() );
  
  return 0;
};

Then, you time the loops with whatever method you prefer.

0

>Then, you time the loops with whatever method you prefer.
Thanks, after testing, the results are almost the same on my pc

ps : I declare inline before those function to eliminate the cost of
calling function

0

>>But it is always 0 after optimize

What does that tell you? That unless your doing this for a legitimate reason, you shouldn't have to worry about it

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.