Data Types in Arduino
Testing Data Types (Multiplication/Division)
Now let’s look at what happens with ‘harder’ math - multiplication and division.
Here are some screen grabs for multiplication:
Check out the elapsed times: 4µs for
byte, 8 for
long, and 12 for
float - longer for larger data types, and also what we expect to see in terms of ‘harder’ math taking longer. Multiplication is still hardware supported, though - there is a native multiply instruction in the processor which makes multiply operations relatively easy. But what about division?
byte division isn’t too bad at 16µs, but 48 for
long? Ouch. The problem here is that division does NOT have a native instruction in the Atmega instruction set, so the compiler has to do some back flips to create one. So, final lesson: not all mathematical operations are created equal. Divide takes a lot longer than multiply or add (or subtract, but that’s really just add with a minus sign), and something like finding a square root or a sine would take even longer. So long, in fact, that it’s often easier just to maintain a list of values for square roots or sine/cosine/tangent and look up the value that you want than it is to calculate it.