C++ – Performance and other issues with using floating point types in C++

arithmeticcfloating pointoptimizationperformance

Being interested in C++ performance programming there is one aspect I really have no clue about- and that is the implications of using floating point calculations vs doubles vs normal integer mathematics?

What performance issues with these types of calculations should I consider? What other issues need to be considered when deciding which kind of operators to use?

All I currently know is that doubles are probably the most expensive because they are larger, floating point is next and then integer calculations are usually the fastest on a CPU because they are much simpler.

Best Answer

The comments by @ratchet, @Sjoerd and @Stephane answer you question.

Your assertion in the question "All I currently know is that doubles are probably the most expensive because they are larger" shows the rules about optimization - are true - "Only for experts" followed by the "Your not an expert yet" .....

Unless you know the minutest details of the underlying hardware AND how the compiler utilizes those, you cannot make any assertions about floating point numbers. You can't even be certain that a floating point operation takes more time than an integer operation. As a rule, there is enough problems with programmers writing floating point code correctly, that it should be avoided unless needed. If needed, performance is of little concern.

As a rule of thumb - use ints if possible - it's rarely slower then FP operations, and often faster, and more predictable. If you must use FP operations, use doubles. Floats do not have a large enough mantissa for anything but the roughest of calculations (unless extreme care is taken) and a prone to insidious rounding errors.

However, like all rules of thumb, they need to be applied appropriately. If it matters - measure it.

Related Topic