Reducing Code Execution Time
Multiplication And Division
Fixed multiplication and division can converted to bit shifting to optimise code. The bit shifting operations can be found by doing a Taylor’s expansion of the equation. The error in the result depends on how many bit shifting operations you wish to perform. The below example uses bit shifting instead of fixed-number multiplication to reduces the number of execution cycles, and shows the difference and error between the result and the actual value.
Powers And Square Roots
pow()
, a function provided with most IDEs, is a slow function. If raising to the power of an integer, multiply the variable by itself rather than use the pow()
function.
There is a brilliant article on square root optimisation: http://www.azillionmonkeys.com/qed/sqroot.html
Fixed Point
mbedded.ninja has an open-source fixed-point library (MFixedPoint) that is hosted on GitLab.
Trigonometry
Fast and accurate sin/cos approximations can be found here.
The CORDIC algorithm can be used, which is a simple and efficient algorithm for calculating trigonometry and hyperbolic functions.