tags:

views:

513

answers:

4

Hi, We can do left shift operators in C/C++ for faster way to multiply integers with powers of 2.

But we cannot use left shift operators for floats or doubles because they are represented in different way, having an exponent component and a mantissa component.

My questions is that,

Is there any way? Like left shift operators for integers to faster multiply float numbers? Even with powers of 2??

+13  A: 

No, you can't. But depending on your problem, you might be able to use SIMD instructions to perform one operation on several packed variables.. Read about the SSE2 instruction set. http://en.wikipedia.org/wiki/SSE2
http://softpixel.com/~cwright/programming/simd/sse2.php

In any event, if you are optimizing floating-point multiplications, you are in 99% of the cases looking in the wrong place. Without going on a major rant regarding premature optimization, at least justify it by performing proper profiling.

Mads Elvheim
+4  A: 

You could do this:

float f = 5.0;
int* i = (int*)&f;
*i += 0x00800000;

But then you have the overhead of moving the float out of the register, into memory, then back into a different register, only to be flushed back to memory ... about 15 or so cycles more than if you'd just done fmul. Of course, that's even assuming your system has IEEE floats at all.

Don't try to optimize this. You should look at the rest of your program to find algorithmic optimizations instead of trying to discover ways to microoptimize things like floats. It will only end in blood and tears.

greyfade
floating point multiplies are shit quick anyway ...
Goz
Gah.. that code gives me the willies. Also, passing data between the floating point registers CPU registers, is often a very costly operation. Which is why even float-to-int conversions suck.
Mads Elvheim
+1  A: 

The speed of your floating point operations apparently depend on the instruction mix. Explained here:

http://stackoverflow.com/questions/1146455/whats-the-relative-speed-of-floating-point-add-vs-floating-point-multiply

One alternative is to use fixedpoint floatingpoint instead "real" floats.

torbjoernwh
+1  A: 

Truly, any decent compiler would recognize static-time power-of-two constants and use the smartest operation.

Aurélien Vallée
I have to guess that you rarely (if ever) really examine the output of a compiler. I have -- nearly none of them is very smart, especially when it comes to floating point. Intel's does about as well as any I've seen recently, and I'd barely rate it as "mediocre" in this respect -- most of the others are substantially worse.
Jerry Coffin