Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do C and C++ optimizers typically know which functions have no side effects?

Say for very common math functions, such as sin, cos, etc... does the compiler realise they have no side effects and have the ability to move them to outer loops? For example

// Unoptimized  double YSinX(double x,int y) {    double total = 0.0;    for (int i = 0; i < y; i++)       total += sin(x);    return total; }  // Manually optimized  double YSinX(double x,int y) {    double total = 0.0, sinx = sin(x);    for (int i = 0; i < y; i++)       total += sinx;    return total; } 

If they can, is there a way of declaring a function as having no side effects, and hence being safe to optimize in this way? Initial profiling of a VS2010 app suggests that the optimization is beneficial.

See also this related question, which is close but doesn't quite answer my own.

Edit: Some great answers. The one I accepted was based as much on the comments it provoked as the answer itself, notably the linked article, and the fact that hoisting may not occur in situations where errno is set (i.e. a side effect). As such, and in the context of what I'm doing, this type of manual optimization still appears to make sense.

like image 427
SmacL Avatar asked Apr 26 '13 09:04

SmacL


People also ask

What is C side effects?

In C and more generally in computer science, a function or expression is said to have a side effect if it modifies a state outside its scope or has an observable interaction with its calling functions or the outside world.

What is Ofast?

Optimization level -Ofast -Ofast performs optimizations from level -O3 , including those optimizations performed with the -ffast-math armclang option. This level also performs other aggressive optimizations that might violate strict compliance with language standards.

How do I disable compiler optimization?

Use the command-line option -O0 (-[capital o][zero]) to disable optimization, and -S to get assembly file. Look here to see more gcc command-line options. Save this answer.

What is O3 in GCC?

-O3 option turns on more expensive optimizations, such as function inlining, in addition to all the optimizations of the lower levels '-O2' and '-O1'. The '-O3' optimization level may increase the speed of the resulting executable, but can also increase its size.


1 Answers

GCC has two attributes, pure and const, that may be used to mark such function. If the function has no side-effect and its result depends only on its arguments, the function should be declared const, if the results may also depend on some global variable the function should be declared pure. Recent versions also have a -Wsuggest-attribute warning option that can point functions which ought to be declared const or pure.

like image 173
adl Avatar answered Oct 22 '22 09:10

adl