Thursday 23 January 2014

Optimising maths for speed

Depending on the settings of your compiler, some maths might already be optimised.  However, I believe most people are using the Arduino development suite as it is installed (I don't even know whether you CAN optimise the Arduino compiler).

You can save time (increase calculation speed) by not calculating "constant" equations every time (an optimised compiler will do this for you).  For example, in the Morgan code, the following line

SCARA_C2 = (pow(SCARA_pos[X_AXIS],2) + pow(SCARA_pos[Y_AXIS],2) - 2*pow(Linkage_1/1000,2)) / (2 * pow(Linkage_1/1000,2));

contains two instances of a "constant" that can be pre-calculated:

2*pow(Linkage_1/1000,2)

and inserted in this line.

The second optimisation I tried was to replace the "pow(x,y)" math function (which raises x to any power y) with the "sq(x)", or square function.  This is significantly faster than the generic first function.  The code becomes:

constcalc = 2 * sq(Linkage_1/1000);       // just after where Linkage_1 is defined

SCARA_C2 = (sq(SCARA_pos[X_AXIS]) + sq(SCARA_pos[Y_AXIS]) - constcalc) / constcalc);

These small changes make about a 30% difference in execution speed.  These are only part of the total calculation for Morgan, however.

Another optimisation (which I have not investigated) is to replace the "atan2" function, which calculates the arctangent from two parameters, with a pre-calculated lookup table.  There is more than enough memory available to have a comprehensive (read accurate) table, but again, the complexity added might not be worth the increase in calculation speed.

 

No comments:

Post a Comment