I currently have code that looks like
while (very_long_loop) {
...
y1 = getSomeValue();
...
x1 = y1*cos(PI/2);
x2 = y2*cos(SOME_CONSTANT);
...
outputValues(x1, x2, ...);
}
the obvious optimization would be to compute the cosines ahead-of-time. I could do this by filling an array with the values but I was wondering would it be possible to make the compiler compute these at compile-time?
Edit: I know that C doesn't have compile-time evaluation but I was hoping there would had been some weird and ugly way to do this with macros.
If you're lucky, you won't have to do anything: Modern compilers do constant propagation for functions in the same translation unit and intrinsic functions (which most likely will include the math functions).
Look at the assembly to check if that's the case for your compiler and increase the optimization levels if necessary.
Nope. A pre-computed lookup table would be the only way. In fact, Cosine
(and Sine
) might even be implemented that way in your libraries.
Profile first, Optimise Later.
No, unfortunately.
I would recommend writing a little program (or script) that generates a list of these values (which you can then #include
into the correct place), that is run as part of your build process.
By the way: cos(pi/2) = 0!
You assume that computing cos
is more expensive than an access. Perhaps this is not true on your architecture. Thus you should do some testing (profiling) - as always with optimization ideas.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With