I want to know which among the following codes
if( n & 1) // Checks if the integer n is odd
if( n % 2 != 0) // Also checks if the integer n is odd
is executed faster in c or c++.
I do not know if they have the same execution speed, but if they have even a small difference , even if it is in milliseconds or microseconds, can you please tell me about it. I saw the first one in a code in a program i read a while ago but could not get the answer when i searched the net. Please help…
I know that in programming, what’s more Important is the algorithm, but I’m just confused about which is faster.
@arun_as: It depends on your compiler. If you use optimization flag -O2, then I think both statements are equivalent. You can try running a test on your system.
the result is (n & 1) is faster than (n % 2 ==1)
this is because our compiler convert our high language code to low language or machine language code which is assembly language code so that code —
for (n & 1) =>
for this assembly language will take two step one take and operation and second to store the result
for (n % 2 == 1) =>
for this our compiler takes several instructions like
movement and then addition and then and and the movement and then storing the result so that this process completes in several steps but above given operation can be performed using two steps
so bitwise and operation is better than modulo operation
What exactly is " optimization flag -O2 " , or in which compiler is it found
optimization flag is on the
compiler, although they work differently on each on. Adding this flag to the compiler command in the Terminal or Command Prompt will make your compiler try to output an optimized program.
gcc -c hello.c -O2
will output a more optimized program than
gcc -c hello.c
can be optimized.
Some programming competitions like USACO automatically add this flag, but I’m not sure if CodeChef does.
I use gcc 4.8.1 compiler ( DevC++ ). So is " optimization flag -O2 " present in it??
@dpraveen Although your explanation of the optimization flag is much clear, I wanted to read more about, couldn’t find more. Can you please give some reference? And if such optimizations are available, why is it that we are not normally using the same everytime, compiler giving us an optimized code is a very great and needy thing I suppose or is it that it relies on us to write efficient codes. Will you please elaborate on this… I have no knowledge of optimization flags, so may sound kiddish here
You can check this for gcc optimization flags.
Thanks… But I have another question. I asked this question on an other website, and some of the people there said that the second statement, ( n % 2 == 1 ) will automatically be converted to ( n & 1 ) by the compiler in the newer versions of c++. So, will there still be a change in compilation and execution time ???