比较乘法和除法 [英] Compare multiplication and division

查看:182
本文介绍了比较乘法和除法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道以下两种方法之间的速度是否有差异。

I want to know if there is any difference in speed between the following two methods

#include<math.h>
#include<iostream>
using namespace std;

int main()
{
    float k=7;
    float b=4;
    cout<<(float)k/b<<" "<<endl;
    cout<<(float)(k*powf(b,-1))<<" "<<endl;

    return 0;
}




  1. trivial diivision k / b

  2. 使用乘法 k * b ^( - 1)

  1. trivial diivision k/b
  2. using multiplication k*b^(-1),

我认为在第二种方法中,没有实际的分割程序。所以我认为第二是更快。

I think that in second method, there is not actual division procedure. So I think the second is faster. Am I right?

推荐答案

计算b ^( - 1)不是微不足道的,有时由优化器转换为1 / b。同样,优化程序可以用 / b 切换 * b ^( - 1)。这可能是硬件相关的(如果数字在编译时已知,可能是依赖于数字的)。

Calculating b^(-1) isn't trivial, and will sometimes (though not always) be converted to 1/b by an optimizer. Just as much, an optimizer might switch *b^(-1) with /b. This is probably hardware-dependent (and possibly even number-dependent, if numbers are known in compilation time).

如果你想测试它,

另外请注意,在某些情况下,这两种方法会稍微给你一些(不打印任何东西到屏幕上)不同的结果,如果你有兴趣精确计算。

Also note that in some cases, these 2 methods will give you slightly different results, if you're interested in precise computation.

这篇关于比较乘法和除法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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