gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:46:53 25 4
gpt4 key购买 nike

我总是假设将 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 operatorsthat expect operands of arithmetic or enumeration type causeconversions and yield result types in a similar way. The purpose is toyield a common type, which is also the type of the result. Thispattern is called the usual arithmetic conversions, which aredefined as follows:

(1.3) –Otherwise, if either operand is double, the other shall be convertedto double.


请注意,在 this Draft C11 Standard 中, §6.3.1.8(通常的算术转换)具有等效(实际上,几乎相同)的文本。

关于c++ - 双除以双和整数 : which one is better?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68790137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com