This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Division optimization problem

Hello everyone,
I implemented a Moving average routine in Keil C51.
And as I read else where that whenever I divide the number with 2^n the compiler uses shift operation, so that code is small and fast.
And Compiler did optimize it in this condition:

average =BINHI/64;  //BINHI, average is unsigned int.

However when BINHI is unsigned long instead of unsigned int the compiler uses actual division which is very costly in 8 bit.
So is there any way to divide unsigned long using shift operations only, if I make sure divisor is 2^n.

Parents
  • Sorry - I did press send a bit early.

    Notice that if you have enough numeric range, then it can be cheaper to not divide by 64 (or shift right by six) but instead multiply by 4 (or shift left by two).

    That means you get the answer in the upper three bytes of a 32-bit variable.

    And the 8051 processor - being an 8-bit processor - is excellent at picking up these three bytes and copy them one step down and then zero the high byte of the result.

    In some situations, you can even drop these two shifts, by performing your running average on input values that have been scaled 4 times larger. Which means that your running total will also be four times larger. And all you need to do is to throw away the contents of the low byte.

Reply
  • Sorry - I did press send a bit early.

    Notice that if you have enough numeric range, then it can be cheaper to not divide by 64 (or shift right by six) but instead multiply by 4 (or shift left by two).

    That means you get the answer in the upper three bytes of a 32-bit variable.

    And the 8051 processor - being an 8-bit processor - is excellent at picking up these three bytes and copy them one step down and then zero the high byte of the result.

    In some situations, you can even drop these two shifts, by performing your running average on input values that have been scaled 4 times larger. Which means that your running total will also be four times larger. And all you need to do is to throw away the contents of the low byte.

Children
No data