将编译器优化划分为乘法 [英] Will the compiler optimize division into multiplication

查看:120
本文介绍了将编译器优化划分为乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据此问题,浮点点除法与浮点乘法 。由于某些原因,除法比乘法慢。

Depending on this question Floating point division vs floating point multiplication. Division is slower than multiplication due to some reasons.

如果可能,编译器通常是否用乘法代替除法?

Will the compiler, usually, replace division by multiplication if it is possibe?

例如:

float a;
// During runtime a=5.4f
float b = a/10.f;

将是:

float a;
// During runtime a=5.4f
float b = a*0.1f;

如果认为编译器可靠的问题,我使用VS2013默认编译器。但是,如果我有一个通用的答案(这个优化的理论有效性),这将是很好的。

If it is considered a compiler dependable question, I am using VS2013 default compiler. However, it would be nice if I got a generic answer (theoretical validity of this optimization)

推荐答案

允许在一般情况下这样做:由于互易的表示错误,两个操作可能产生不一致的结果。

No, the compiler is not allowed to do that for the general case: the two operations could produce results that are not bit-identical due to the representation error of the reciprocal.

在您的示例中, code> 0.1 没有与 float 完全相同的表示形式。这导致乘以 0.1 并除以 10 的乘法结果不同:

In your example, 0.1 does not have an exact representation as float. This causes the results of multiplication by 0.1 and division by 10 to differ:

float f = 21736517;
float a = f / 10.f;
float b = f * 0.1f;
cout << (a == b) << endl; // Prints zero

演示。

注意: njuffa 在下面的注释中正确地注释,有时编译器可以对大量数字进行一些优化,如本文。例如,乘以2的幂等于对IEEE-754 float 表示的指数部分的加法。

Note: As njuffa correctly notes in the comment below, there are situations when the compiler could make some optimizations for a wide set of numbers, as described in this paper. For example, multiplying or dividing by a power of two is equivalent to addition to the exponent portion of the IEEE-754 float representation.

这篇关于将编译器优化划分为乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆