User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the C++ section within the Software Development category of DaniWeb, a massive community of 427,333 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 3,223 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our C++ advertiser: Programming Forums

C++ Performance Tips

Join Date: Apr 2004
Posts: 3,647
Reputation: Dave Sinkula is a glorious beacon of light Dave Sinkula is a glorious beacon of light Dave Sinkula is a glorious beacon of light Dave Sinkula is a glorious beacon of light Dave Sinkula is a glorious beacon of light Dave Sinkula is a glorious beacon of light 
Rep Power: 17
Solved Threads: 144
Colleague
Dave Sinkula's Avatar
Dave Sinkula Dave Sinkula is offline Offline
long time no c

Re: A General Performance Tip - Arithmetic involving powers of 2

  #16  
Dec 15th, 2006
Originally Posted by vicky_dev View Post
Multiplication, division and modulus operations on powers of 2 can be made much faster using bitwise operators.

1. Modulo
Finding the modulus is particularly expensive. This operation can be performed mush faster using the & operator, because
a % n == a & (n-1) where n is power of 2.

2. Division
Division by a power of 2 can done faster using the >> operator.
a / n == a >> m, where n = 2^m

3. Multiplication
This is similar to division, except, use left shift << operator
a * n == a <<m , n = 2^m
Valid, albeit ancient, advice -- much like the XOR swap.

It's one of those things that language implementers knew about ages ago, and should be done by the compiler automagically (or it may take some optimization option).

Bottom line: don't do this unless your compiler sucks. Write code to multiply by 4 like this num*=4. Obfuscating it as num<<=2 will make your code look strangeto newbies, and it will look like a newbish hack to old timers (both making what you write a little suspect).

And don't forget that right-shifting signed values is implementation defined!
Last edited by Dave Sinkula : Dec 15th, 2006 at 8:54 pm.
Reply With Quote  
All times are GMT -4. The time now is 3:02 am.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC