Data Types in Arduino

Pages
Contributors: b_e_n
Favorited Favorite 38

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:

Multiply with bytes screen capture[(https://cdn.sparkfun.com/tutorialimages/datatypes/mult_int.jpg)

Multiply with bytes screen capture[(https://cdn.sparkfun.com/tutorialimages/datatypes/mult_float.jpg)

Check out the elapsed times: 4µs for byte, 8 for int or 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?

Divide with bytes screen captureDivide with ints screen capture

Divide with longs screen captureDivide with floats screen capture

Oh, my. 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.