c++ - 双除以双和整数 : which one is better?

标签 c++ c

我总是假设将 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 值。

来自 this Draft C++ Standard :

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/

相关文章:

c++ - 如何获得二维数组中两点的差异

c++ - 追踪 COM 接口(interface)/SysAlloc 泄漏

c - 函数只工作一次 - C

使用 Strcmp 的 C 段错误

c - 如何动态加载我自己的库,并调用其中的方法?

c++ - 为什么我的结果数据返回为 void* 损坏?

c++ - 无法将库与 cmake 和 Visual Studio 2017 链接

c++ - C中isupper的宏定义是什么?

c++ - 我什么时候不希望在 Microsoft Visual Studio 中启用 “Control Flow Guard”?

c - 将 2D 数组切片从 3D 数组传递给函数