6

I am reading a C book. In the Arithmetic Expression section, they say:

"Division typically uses more resources.  To avoid division, we multiply rather than divide. For example, we multiply by 0.5 rather than divide by 2.0."

Why Division typically uses more resources?. Can anyone give me a detail explanation, please?

Thanks a lot.

ipkiss
  • 13,311
  • 33
  • 88
  • 123
  • 1
    What you should be looking into is how the ALU on different processors implement division. – Ed S. Feb 25 '11 at 00:04
  • 2
    Just keep in mind that current C compilers will normally do such micro optimization for you – nos Feb 25 '11 at 00:16
  • @nos - Generally only with optimizations enabled; some people measure this stuff in DEBUG mode and get the wrong idea. – Josh Feb 25 '11 at 00:17

1 Answers1

6

Binary Multiplication is simple using the peasant algorithm - you basically shift, then sum: http://en.wikipedia.org/wiki/Multiplication_algorithm#Peasant_or_binary_multiplication

Binary Division is much harder, as it's a sequence of subtractions (like long division you may have done in school). The main algorithm class is called 'radix', which you can see an example of here: http://www.bearcave.com/software/divide.htm

Remember though - measure first, then optimise. It's much easier to maintain code that matches the problem domain than code that is already optimised.

Josh
  • 3,540
  • 1
  • 21
  • 12