I'm writing an app which translates formulae into executable code. I've been experimenting with fairly obvious optimizations such as factoring (reducing number of multiplications) in order to make the code run faster. Can anyone suggest any other performance-related optimizations that could be performed when translating formulae to code? Thanks.
Looking for mathematical optimizations when translating formulae to code
5
$\begingroup$
optimization
-
0@J.M. thanks, subexpression analysis is one of the things I'm already working on – 2011-09-16
2 Answers
2
The code
double x = a / b + c / d;
typically takes about twice as long to execute as the equivalent expression
double x = (a * d + b * c) / (b * d);
because floating point division is very slow whereas addition and multiplication are fast.
As well as that there are the obvious things to do like pre-computing constant values, and replacing
double x = a + 0.0; double y = b * 1.0; double z = c / 1.0;
with the equivalent expressions
double x = a; double y = b; double z = c;
This isn't quite so nonsensical as it may appear: the constants 1.0
and 0.0
might not be the values originally written, but rather the results of some intermediate computation.
You could also optimize pow(x, 2)
to x * x
and the like, although any decent compiler should do this for you.
-
0Could be true. It is 'optimised' for speed, not accuracy :) – 2011-09-16
1
I think you'd better leave such optimizations to the compiler. Or do you have evidence that the compiler cannot do justice to your formulas?
-
3@Dmitri, sure, every compiler is gcc but you can bet that optimizing compilers will do a good job. There has been *decades* of research on that. My point is: don't try to outsmart the compiler; you may even force it to generated *worse* code than if you just wrote what you meant. – 2011-09-16