我总是假设将 double 除以整数会导致更快的代码,因为编译器会选择更好的微码来计算:
double a;
double b = a/3.0;
double c = a/3; // will compute faster than b
对于单个操作来说无所谓,但是对于重复性操作来说就不同了。我的假设是否始终正确或取决于编译器或 CPU 或其他什么?
同样的问题适用于乘法;即 3 * a
会比 3.0 * a
更快吗?
最佳答案
您的假设不是正确的,因为您的两个除法操作都将使用两个double
操作数执行。在第二种情况下,c = a/3
,整数文字将在生成任何代码之前由编译器转换为 double
值。
8.3 Usual arithmetic conversions [expr.arith.conv]
1 Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:
…
(1.3) – Otherwise, if either operand is double, the other shall be converted to double.
请注意,在 this Draft C11 Standard 中, §6.3.1.8(通常的算术转换)具有等效(实际上,几乎相同)的文本。
关于c++ - 双除以双和整数 : which one is better?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68790137/