-1

I would think they are the same on 64bit architect.

For example I'm writing a function template, should I provide a specification for float as well as double, or should I just provide one specification takes a double and let other numbers converted to double automatically? Assuming the only numeric types considered are float, double, int, long, unsigned int, unsigned long.

sashoalm
  • 75,001
  • 122
  • 434
  • 781
swang
  • 5,157
  • 5
  • 33
  • 55
  • 1
    That would depend on the architecture, so you need to specify that - x86, ARM or whatever. – sashoalm Feb 09 '15 at 17:31
  • 2
    Even on a specific architecture, it can depend on the context. But even using `double`, you **cannot assume** that a converted integer type will give you the same comparison result. – Drew Dormann Feb 09 '15 at 17:32
  • 2
    Related: [When do you use float and when do you use double](http://programmers.stackexchange.com/questions/188721/when-do-you-use-float-and-when-do-you-use-double) [Why are double preferred over float?](http://stackoverflow.com/questions/22818382/why-are-double-preferred-over-float) – Deduplicator Feb 09 '15 at 17:32
  • 1
    The rule: Use double unless you have a good reason, that you can explain to someone else, to use float. If you _ask_ which is more efficient, use double. – gnasher729 Feb 09 '15 at 17:39
  • Do you really need to specify for all types? Can't you just specify for floating and integral types? See http://en.cppreference.com/w/cpp/types – MofX Feb 09 '15 at 18:29

2 Answers2

2

It is typically either the same or slightly faster to compare a float to a float than a double to a double, but the difference is typically miniscule either way. The bigger performance problem you might be looking at is the conversion from float to double, which can either be free or pretty expensive, depending on where and how it is being done.

Either way, it's really not worth worrying too much about unless you have profiled and found a bottleneck in some huge loop involving this function, in which case you can then test the performance difference yourself and react accordingly.

Gerald
  • 23,011
  • 10
  • 73
  • 102
  • Can you please explain what decides the cost of float to double conversion? The compiler or hardware implementation? – swang Feb 09 '15 at 23:30
-3

The best solution: use templated types. This would use the provided type automatically and all speed optimization will be done by the compiler.

Still good solution: have one function for integral and one for floating-point types using the largest type you want to support (usually long and double).

Using floating-point operations on integral types loses precision and should be avoided.

StenSoft
  • 9,369
  • 25
  • 30