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!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Division by bit shift

Ranch Hand
Posts: 296
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)

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

Thanks,

Drew

Ranch Hand
Posts: 1608
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

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