Ryoku
Ryoku

Reputation: 427

Optimization: Is it faster to multiply a float by an integer or another float

If I am trying to multiply a float by a whole number is it faster to multiply it by a whole number being represented by an integer

int x;
...
float y = 0.5784f * x; //Where x contains a dynamically chosen whole number

or by another float (provided there is no loss in accuracy)

float x;
...
float y = 0.5784f * x; //Where x contains a dynamically chosen and floating point representable whole number

or does it vary greatly between hardware? Is there a common circuit (found in most floating point units) that handles float and integer multiplication or is the general practice for the hardware to first convert the integer into a float and then use a circuit that performs float * float? What if the whole number being represented is extremely small such as a value of 0 or 1 determined dynamically and used to determine whether or not the float is added to a sum without branching?

int x;
...
float y = 0.5784f + 0.3412f * x; //Where x contains either 0 or 1 (determined dynamically).

Thanks for the help in advance.

Upvotes: 3

Views: 2110

Answers (1)

chux
chux

Reputation: 153338

Is it faster to multiply a float by an integer or another float

In general, float * float is faster, yet I suspect little or no difference. The speed of a program is a result of the entire code, not just this line. Faster here may cost one more in other places.

Trust your compile or get a better compiler to emit code that performs 0.5784f * some_int well.

In the 0.5784f * some_int case, the language obliges some_int to act as if it is converted to float first*1 before the multiplication. But a sharp compiler may known of implementation specific tricks to perform the multiplications better/faster directly without a separate explicit conversion - as long as it gets an allowable result..


In the float y = 0.5784f + 0.3412f * x; //Where x contains either 0 or 1 (determined dynamically). a compile might see that too and take advantage to emit efficient code.


Only in select cases and with experience will you out-guess the compiler. Code for clarity first.

You could always profile different codes/compiler options and compare.


Tip: In my experience, I find more performance gains with a larger view of code than the posted concern - which verges on micro-optimization.


*1 See FLT_EVAL_METHOD for other possibilities.

Upvotes: 3

Related Questions