views:

74

answers:

2

I want to make a sin func. so here's my code:

inline double _cdecl Sin(double Rad)
{
    _asm
    {
        fld QWORD PTR [Rad]
        fsin 
    }
}

my func works faster(ratio of about 6) than the standard sin. (there are probably some problems in it, but it's enough for me) but if I'll do for example

for(int i = 0; i < 1000000; ++i)
       sin(1)

the standard sin will be faster in a ratio of about 3 and if I'll do

for(int i = 0; i < 1000000; ++i)
       sin(i)

my func will be faster in ratio of about 3. what happens here?

A: 

Wouldn't the compiler optimize better the first version with standard sin and detect it's a constant ?

Loïc Février
+3  A: 

The compiler might know that sin(1) is an intrinsic pure function with no side effects, and therefore won't even bother to call it within the loop. So you might end up just timing the loop itself. Check the generated assembly code using the appropriate compiler switch for assembly output.

Greg Hewgill
+1 For noting optimization. Since the argument to `sin(1)` is constant, there is no need for the program to call it more than once, so the compiler can replace the loop with a single function call. Also, since the return value is not used, the compiler may throw out the single function call.
Thomas Matthews
I believe gcc can evaluate it once at compile time.
phkahler