优化:将浮点数乘以整数还是另一个浮点数更快

2024-03-23

如果我尝试将浮点数乘以整数,则将其乘以整数表示的整数是否更快

int x;
...
float y = 0.5784f * x; //Where x contains a dynamically chosen whole number

或通过另一个浮点数(前提是精度没有损失)

float x;
...
float y = 0.5784f * x; //Where x contains a dynamically chosen and floating point representable whole number

还是硬件之间差异很大?是否有一个通用电路(在大多数浮点单元中都有)处理浮点和整数乘法,或者硬件的一般做法是首先将整数转换为浮点,然后使用执行 float * float 的电路?如果所表示的整数非常小,例如动态确定的值 0 或 1,并用于确定是否将浮点数添加到总和中而不进行分支,该怎么办?

int x;
...
float y = 0.5784f + 0.3412f * x; //Where x contains either 0 or 1 (determined dynamically).

我在这里先向您的帮助表示感谢。


将浮点数乘以整数或另一个浮点数更快吗

In general, float * float更快,但我怀疑差别很小或没有差别。程序的速度是整个代码的结果,而不仅仅是这一行。这里更快可能在其他地方要多花一点钱。

相信您的编译或获得更好的编译器来生成可执行的代码0.5784f * some_int well.

In the 0.5784f * some_int case, the language obliges some_int to act as if it is converted to float first*1 before the multiplication. But a sharp compiler may known of implementation specific tricks to perform the multiplications better/faster directly without a separate explicit conversion - as long as it gets an allowable result..


In the float y = 0.5784f + 0.3412f * x; //Where x contains either 0 or 1 (determined dynamically).一个编译might也看到这一点并利用它来发出高效的代码。


只有在特定的情况下并且凭借经验,您才能猜出编译器。首先代码要清晰。

你总是可以profile https://en.wikipedia.org/wiki/Profiling_(computer_programming)不同的代码/编译器选项并进行比较。


提示:根据我的经验,我发现与发布的问题相比,更大的代码视图可以带来更多的性能提升 - 这接近于微观优化 https://softwareengineering.stackexchange.com/questions/99445/is-micro-optimisation-important-when-coding.


*1 See FLT_EVAL_METHOD for other possibilities.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

优化:将浮点数乘以整数还是另一个浮点数更快 的相关文章

随机推荐