Hitokage
Hitokage

Reputation: 803

Speed difference between assign function value and not assign to a variable

So this is really a mystery for me. I am Measuring time of my own sine function and comparing it to the standard sin(). There is a strange behavior though. When I use the functions just standalone like:

sin(something);

I get an average time like (measuring 1000000 calls in 10 rounds) 3.1276 ms for the standard sine function and 51.5589 ms for my implementation. But when I use something like this:

float result = sin(something);

I get suddenly 76.5621 ms for standard sin() and 49.3675 ms for my one. I understand that it takes some time to assign the value to a variable but why doesn't it add time to my sine too? It's more or less the same while the standard one increases rapidly.

EDIT: My code for measuring:

ofstream file("result.txt",ios::trunc);
file << "Measured " << repeat << " rounds with " << callNum << " calls in each \n";
for (int i=0;i<repeat;i++)
{
    auto start = chrono::steady_clock::now();

    //call the function here dattebayo!
    for (int o=0; o<callNum;o++)
    {
      double g = sin((double)o);
    }

    auto end = chrono::steady_clock::now();

    auto difTime = end-start;
    double timeD = chrono::duration <double,milli> (difTime).count();
    file << i << ": " << timeD << " ms\n";
    sum += timeD;
}

Upvotes: 0

Views: 104

Answers (1)

Mats Petersson
Mats Petersson

Reputation: 129344

In any modern compiler, the compiler will know functions such as sin, cos, printf("%s\n", str) and many more, and either translate to simpler form [constant if the value is constant, printf("%s\n", str); becomes puts(str);] or completely remove [if known that the function itself does not have "side-effects", in other words, it JUST calculates the returned value, and has no effect on the system in other ways].

This often happens even for standard function even when the compiler is in low or even no optimisation modes.

You need to make sure that the result of your function is REALLY used for it to be called in optimised mode. Add the returned values together in the loop...

Upvotes: 3

Related Questions