Do compilers automatically optimise repeated calls to mathematical functions?

后端 未结 2 1180
半阙折子戏
半阙折子戏 2021-02-19 01:41

Say I had this snippet of code:

#include 

// ...

float f = rand();
std::cout << sin(f) << \" \" << sin(f);

As

2条回答
  •  梦毁少年i
    2021-02-19 02:25

    I'm fairly certain GCC marks sin with the non-standard pure attribute, ie __attribute__ ((pure));

    This has the following effect:

    Many functions have no effects except the return value and their return value depends only on the parameters and/or global variables. Such a function can be subject to common subexpression elimination and loop optimization just as an arithmetic operator would be.

    http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html

    And so there is a very good chance that such pure calls will be optimized with common subexpression elimination.

    (update: actually cmath is using constexpr, which implies the same optimizations)

提交回复
热议问题