bitwise speed!

HOLY CRAP!! My freaking computer is astounding!!!

I just ran a quick computational bitwise speed test. I can run 1BILLION odd or even tests on as many numbers in less than 4 seconds!!

I was trying to see which was faster..

1
2
3
bool is_odd(const int &number){
 return (number == (number | 1));
}


orrr

1
2
3
bool is_odd2(const int &number){
 return !(number % 2 == 0);
}


turns out the second is about 5% faster than the first.
Though I imagine getting the next odd number with (number | 1) is probably faster than many other methods. Just saying I am amazed by the unfathomable speed of my computer =)

(edit) wooow I was using ^ instead of %
Last edited on
That | solution is a little obfuscated. Why not use the more obvious & approach?

1
2
3
4
bool is_odd(int number)  // note:  no need for reference, pass by value
{
  return (number & 1);  // simple
}
(because I didn't see it) haha that would make more sense.
You might also buy more speed by passing the parameter by value instead of reference.
Really?! I thought the opposite was true! I suppose I'll try that!

(edit) Smaller number possibly?
Last edited on
Passing by reference is not always faster.

The reason why passing by reference is sometimes faster than passing by value is because you avoid an object copy. A reference is a very small type, like a pointer, so copying it is cheap.

However, references aren't really smaller than other basic types (like int). So passing a reference doesn't save you on any copying. Passing an int by reference and an int by value both involves about the same amount of copying. They're both very cheap.

In addition, references can require an indirection (like dereferencing a pointer)... which is an additional memory access. Therefore passing by reference can actually be slower for basic types (and other small types).
Last edited on
Huh, good to know!
Topic archived. No new replies allowed.