chinu wrote:
hi all,
i did a small experiment to grasp the advantages of declaring a
function as inline.
inline int fun1();
This is pointless. A function shouldn't be declared 'inline' and
not be defined. That defeats the purpose of having it 'inline'. Do
you know what 'inline' does?
int main(){
unsigned int start=0,end=0;
asm("rdtsc\n\t"
"mov %%eax, %0\n\t":"=m"(start):);
// cout<<"Start value is "<<start<<endl;
fun1();
asm("rdtsc\n\t"
"mov %%eax, %0\n\t":"=m"(end):);
cout<<"time taken is "<<end-start<<endl;
}
inline int fun1(){
int a=1990;
a++;
for(a=0;a<1000;a++);
/* just to consume some time*/
}
i ran above program with inline declaration of fun1 and without inline
declaration of fun1, both times, total time taken was same...
am i doing something wrong?
Yes, you probably don't understand what the point of 'inline' is. When
the compiler is generating code and sees a call to that function, if it
has the body of the function and it's declared 'inline' (a possible hint
to the compiler, saying, "it's OK, compiler, go ahead and stick the body
of that function in there instead of making a true call"), then it can
generate code differently than it would without 'inline'. Compare
inline int onemorethan(int a) {
return a+1;
// code generated:
// function_prologue ; preserving some registers, checking env
// load register from argument
// add 1 to register
// store register to where_return_value_goes ; maybe NOP
// function_epilogue ; restoring preserved registers, blahblah
}
int main() {
int b = 41;
int c = onemorethan(b);
// code generated with 'inline':
// load register from 'b'
// increment register
// store register in 'c'
//// code generated if there were no 'inline'
//// load register from 'b'
//// store register to where_arguments_go ; ususally 'push'
//// call 'onemorethan' ;;; see above
//// load register from where_return_value_comes ; usually NOP
//// store register to 'c'
}
If by the time the compiler encounters a call to 'onemorethan' and
does not know that the body of the function is (and it would be the
case if I just provided a declaration (prototype) and not the body),
the compiler cannot replace the call with the body.
As to ODR violations, the compilers/linkers are not yet sophisticated
enough to really catch those things. They pretend to, but you should
not rely on them to do it right. We can discuss that if you want, let
us know.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask