This week's book giveaways are in the Scala and Android forums.
We're giving away four copies each of Machine Learning Systems: Designs that scale and Xamarin in Action: Creating native cross-platform mobile apps and have the authors on-line!
See this thread and this one for details.
Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Division by bit shift  RSS feed

 
Ranch Hand
Posts: 296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I read that performance can be improved by using bit shifting in place of division.

Is it possible to do this with denominators other than 2?

For example, say I want to divide 2 by 3. (ie. 2/3)

What about 3/4?

How would I do this and would I get the same performance benefits?

Thanks,

Drew
 
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Broad sweeping statements regarding performance are almost always false, and certainly in this case. Quite often, extrapolations from benchmarks are also false due to the nature of the implicit changes in the extrapolation.

If you are attempting to increase performance, I strongly suggest you use a profiler to determine that your arithmetic is negligible by many orders of magnitude to some other potential bottlenecks.
 
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Originally posted by Drew Lane:
I read that performance can be improved by using bit shifting in place of division.



That *might* be true at the machine language level, depending on the platform. A good compiler will do this optimization automatically where appropriate, so it's best not to worry about it, but to worry about making your code communicate intent.


Is it possible to do this with denominators other than 2?



No, not in architectures that use the binary system to represent numbers.

Remember how in the decimal system you can divide by powers of ten simply by moving the decimal point? That's fully equivalent to a bit shift.

Moving to our Performance forum...
 
Destroy anything that stands in your way. Except this tiny ad:
free 1 hour java lesson
https://coderanch.com/t/695988/free-hour-java-lesson
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!