tags:

views:

134

answers:

2

Will the comparison of two float numbers consume more CPU time than two ints?

A: 

With today's CPUs (excluding maybe embedded machines and the Atom) you can't really make predictions on how fast a single inctruction in code may be.

First of all, it may be removed by the compiler if it's known to be irrelevant, it may be rewritten by the compiler into something different which is known to be faster, etc. That's one pitfall.

Secondly, CPUs can execute more than one instruction per cycle, or make them asynchronously and do other things while waiting for the FPU, etc.

In your specific case, comparing two numbers should be instant, i. e. in one cycle. But you probably can't use that result in that very same cycle already. But this should hold true for both integers and floating-point numbers.

Remember that it's just a series of bits and while floating-point numbers may be a little different due to their structure, it's still a pretty easy problem (compare sign, compare exponent, compare mantissa).

Joey
A: 

IIRC, standard IEEE 754 floating point numbers are stored in such a way that if you treat them as integers, they compare the same way:

| sign | exponent | significand |

The significand (a word I had completely forgotten before consulting the Wikipedia article) is the first few significant digits of the number.

If two floating point numbers a < b, then you have one of:

  • a negative, b not negative;
  • both same sign, but a's exponent < b's exponent; or
  • both same sign and exponent, but a < b.

So you can simply take the 32 bits of each number as integers, and compare them using normal integer arithmetic. I do not know if this is what compilers do in practice. There are a few special representations for certain numbers and these edge cases may mean the FP processor has to do it differently.

See http://en.wikipedia.org/wiki/Floating%5Fpoint#Internal%5Frepresentation

Edmund
thank you, edmund.
lovespring
You can compare floating-point numbers as integers so long as one or both is positive; if both are negative the comparison won't work properly.
Stephen Canon