Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile-time trigonometry in C

Tags:

c

optimization

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.

like image 517
lhahne Avatar asked Jan 08 '11 10:01

lhahne


4 Answers

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.

like image 180
Christoph Avatar answered Nov 07 '22 23:11

Christoph


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.

like image 41
Mitch Wheat Avatar answered Nov 07 '22 23:11

Mitch Wheat


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!

like image 1
Oliver Charlesworth Avatar answered Nov 07 '22 21:11

Oliver Charlesworth


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.

like image 1
maxschlepzig Avatar answered Nov 07 '22 21:11

maxschlepzig