Cisco Systems Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
The answer doesn't seem right. If OR operation is to be performed on two registers(holding 1 and 0xFFFFFFFF), the comparison of all bit will be performed as a result of one assembly command. I do not think the compiler would have the ability to short circuit bitwise comparison. So it doesn't matter if value is 0, 1 or any other value, bitwise OR by compiler cannot be made quicker than assembly command of doing bitwise OR by assembly command.
// here is a program that i made to test this thing
#include <stdio.h>
int main()
{int a=0,count=0;//try to change a's values in consecutive runs of the program,once 0 and //once non zero so that both the whle loops gets a chance to execute
if(a==0)
{
while(1&&count<=1000)
{
printf("testing your query");
count++;
}
}
else
{
while(2&&count<=1000)
{
printf("testing your query");
count++;
}
}
return 0;
}
//running this program, consecutively with diffrent a's value i found out that while(2) was //faster than while(1)
If we write code using while(1) and while(2) and generate their assembly instructions (without using any compiler optimization options), both assembly turn out to be the same. Furthermore, if optimization options are added while compiling, both will get converted to the same set of assembly instructions. Thus it shouldn't matter which one is used.
Note: This is not the case in all scenarios. Ex - ++i is faster than i++ (check out the assembly, latter one has one extra instruction).
I executed the following code using clock function and it gave me the following result. Based on this the result is while(1) is faster.
#include <stdio.h>
#include <time.h>
int checkFaster()
{
int a=1;
clock_t begin,end;
while(a)
{
begin=clock();
a=0;
}
end=clock();
double time_spent1=(double)(end-begin)/CLOCKS_PER_SEC;
a=2;
while(a)
{
begin=clock();
a=0;
}
end=clock();
double time_spent2=(double)(end-begin)/CLOCKS_PER_SEC;
return (time_spent1>time_spent2?1:0);
}
int main()
{
if(checkFaster())
printf("No while2 is faster");
else
printf("Yes while1 is faster");
}
I don't think we can determine this way... On a multi-threaded machine there can be X context-switches while executing loop1 & Y context switches while executing loop2... and this difference will be crucial than anything else.
If you execute this program multiple times... you will get different results.
AFAIK , when any number is compared to 0 , it will be OR'd with 0xfffffff , .. so 1 and 0 in first case which is 1 it will skip .. but in 2 | 0 , it will check 0th bit and first bit as well. hence there is one more instruction check in this case... plz correct me if i m wrng
- gopi.komanduri July 20, 2014