hanno
hanno

Reputation: 6513

Prevent optimizations for one operation in c

I'm implementing an algorithm using compensated summation to reduce the amount of roundoff errors adding up. I'm wondering if I can tell the compiler somehow not to optimize the floating point operations in one specific part of the code. More precisely, I'd like to keep the order of operations preserved. Here is an example code snippet (all variables are double):

while(1){
    a = y;
    e = e + d;
    y = a + e;
    e = e + (a - y);
}

I'm worried that the last line could be optimized to read e=e-e or e = (e+a)-y. In which circumstances could this happen and how can I prevent it?

Upvotes: 0

Views: 101

Answers (2)

There is no strictly standard way to prevent optimization (in general). However, if using a recent GCC compiler, you could use #pragma GCC optimize or the optimize function attribute.

BTW, I am not sure it is worth the trouble. You could look at the lower-level Gimple (perhaps using MELT or some -fdump-tree-*), or at the generated assembler code (use -fverbose-asm to get a more readable assembler ode).

Upvotes: 1

gnasher729
gnasher729

Reputation: 52538

If the compiler claims to be IEEE 754 compliant, then it has to perform the operations exactly as you wrote them - unless it can prove that the result will be the same (in which case the different calculation will not hurt you).

Sometimes this makes code run slower than it would if the compiler would be allowed to give slightly different results. And some compilers have an option to allow the compiler that kind of optimisation. If your compiler has such options, you need to turn them off.

The compiler must respect parentheses. For example, in "e = e + (a - y);" it must subtract y from a, add the result to e, and store the sum into e.

Upvotes: 8

Related Questions