Multiplication/Division by known values is slower than bitshifting, right?

Multiplication/Division by known values is slower than bitshifting, right?
What would be a fast replacement for “if” in a time critical function? It seems to eat a lot of time.

Depends on the known values - also be aware that on avr, bit shifts take one cycle per direction shifted per byte in your data type.

What’s the code look like?

For example setting a threshold like
if (noisevalue>50) DoSomething;
For now noisevalue is a byte.

And … = CHSV(color, 255, noisevalue>>2);

Comparing one byte to a known value (eg x > 50) is very fast-- by itself anyway.

As for bit shifting vs multiplication or division, it depends on the value and the platform. ARM can shift a 32 bit value any number of positions in one instructions. AVR can only shift an eight bit value one bit position at a time per instruction. So if you do a 3-bit shift of a 16 bit value (int), ARM can do it in one instruction, but on AVR it turns into an actual three-iteration loop.

GENERALLY, multiplication is quick and division is slow. This is why if I want to find one third of a one byte value I don’t do third = x/3. Instead I do:
third = scale8( x, (256/3) );
The 256/3 is computed at compile time to be 85, so it compiles as
third = scale8( x, 85);
On AVR, scale8 uses a one-instruction 8-bit multiply; integer division on AVR costs a couple hundred instructions, so in this case it’s much faster…

BUT what we’ve learned above all else is MEASURE MEASURE MEASURE. (Eg benchmark it!). Often out intuitions about speed are all upside down.

Where can I look to look to find this type of information on pieces of my code? Such as machine instructions, etc. Does the Arduino verbose compile log offer this? Or perhaps, does this require a college degree? :wink:

I use a couple of methods. One is flipping pins and hooking up a logic probe, that is one way to get good information on timing. It can require some patience though :slight_smile:

Another is to use objdump and actually look at the compiled code.

Another method that folks use is just timing with millis/micros - I’ve mostly stopped using that myself because I’ve seen enough of the timing underbelly of the Arduino environment to know that the accuracy is handwavy at best :). (But, I’m also doing timing measurements where I’m counting clock cycles instead of ms/us)

FWIW, I use a combination of stopwatch benchmarking and reading the obj dump disassembly of what the compiler generated.