We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › division vs. multiplication
Page Index Toggle Pages: 1
division vs. multiplication (Read 820 times)
division vs. multiplication
Dec 25th, 2005, 12:26am
 
this one goes out to the hardcore programmers among us (you know who you are, sitting at your computers at christmas Wink ).

we have these two expressions:

Code:
y = x/2 


and

Code:
y = x*.5 



my humble knowledge of math tells me, that they both do the same thing. but recently someone told me, that a division uses more computer resources than the equivalent multiplication. is this true? is it generaly a good idea, if given the choice, to go with the "multiplication-approach"?

cheers,
Greg
Re: division vs. multiplication
Reply #1 - Dec 25th, 2005, 4:25am
 
Well, I can't give a definitive answer right now, but there's a major difference if those are ints...

y = x / 2 would round down, so 7 / 2 would be 3.

y = x * 0.5 would convert x to a float, divide by two, then round down. This is essentially the same thing, but slower because of the typecasting.

Generally multiplication is touted as slightly faster, but I'm guessing this isn't too applicable anymore. I actually did this benchmark in another language and found that division was faster, so you never know Smiley
Re: division vs. multiplication
Reply #2 - Dec 28th, 2005, 9:19pm
 
You folks might be interested in this old post. Testing the speed code in it I get with Processing Beta:
Code:

double y=x/2 : 571ms
double y=x*0.5 : 320ms
double y=x+2 : 351ms
float y=x/2 : 550ms
float y=x*0.5 : 311ms
float y=x+2 : 250ms
int y=x/2 : 431ms
int y=x*2 : 250ms
int y=x+2 : 241ms
int y=x>>1 : 230ms
int y=x<<1 : 230ms

Okay, so I get slightly different results everytime - my computer is busy listening to msn and stuff. But according to the print out, bit-shifting is faster than multiplication which is faster than division. Toxi's post explains it fairly well.
Re: division vs. multiplication
Reply #3 - Dec 29th, 2005, 6:06pm
 
Very strange.  You'd expect the compiler (or JIT) to optimize x/2.0 to x*0.5, if that's the case.
Page Index Toggle Pages: 1