c++ - 在 C++ 中调用函数(或虚函数)是一个 coSTLy 操作

标签 c++ optimization inheritance virtual

我正在开发一个很大程度上基于数学(sin、cos、sqrt 等)的应用程序。 这些函数需要一些时间来运行,但精度很高。

我的一些客户不需要那么高的精度,但他们需要它尽可能快。

所以我有我的 Sin 函数,它是一个简单的数组(在程序开始运行之前创建),它取 0 到 360 之间的度数并返回它的 sin(假设数组有360 值)。

我想创建一个界面:

interface MyMath
{
    double PreciseSin(double x);
    double PreciseCos(double x);
}

它将被继承

  1. “精确数学”实现将调用正常的 sin、cos 函数。
  2. “快速数学”将使用我之前解释过的数组技巧。

我的代码将使用“mymath”类型的变量来进行计算,并且在开始时将使用 preciseMath 或 fastMath 对其进行初始化。

最后我的问题是:

  1. 如果调用一个调用“Math.sin”而不是直接调用它的虚函数,我将在时间上付出多少代价?
  2. 编译器是否能够优化它并理解如果我用 PriciseMath 初始化 MyMath 我只想调用正常的 Sin 和 Cos 函数?
  3. 我能否更改我的设计以帮助编译器理解和优化我的代码?

最佳答案

很可能你的 sqrt 和 trig 函数比函数调用有更高的成本,即使它是虚拟的。然而,这看起来是使用模板的完美场所。如果正确使用它们,您可以完全消除函数调用的运行时间成本,因为它们都可以内联。

class PreciseMath{
    public:
    inline double sin(double sin){
        //code goes here
    }
    inline double cos(double sin){
        //code goes here
    }
    inline double sqrt(double sin){
        //code goes here
    }
};
class FastMath{
    public:
    inline double sin(double sin){
        //code goes here
    }
    inline double cos(double sin){
        //code goes here
    }
    inline double sqrt(double sin){
        //code goes here
    }
};
template<class T>
class ExpensiveOP{
    public:
    T math;
    void do(){
        double x = math.sin(9);
        x=math.cos(x);
        //etc
    }
}
ExpensiveOP<PreciseMath> preciseOp;
ExpensiveOP<FastMath> fasterOp;

关于c++ - 在 C++ 中调用函数(或虚函数)是一个 coSTLy 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9547956/

相关文章:

c++ - C++ 中 & 的 C 替换

c++ - 如何在不使用额外模板参数的情况下使用模板模板参数声明/定义类

javascript - 为什么 minification + gzip 使文件大小比 gzip 更小

performance - 具有性能优化潜力的浮点算法

objective-c - 对象(持有 NSMutableArray)在父/子类中具有不同的内容

c++ - 在 C++ 中更好地控制成员对象的构造

c++ - 在 C++ Builder 和 VC++ 中使用 std::string 的区别

PHP 速度 : what is faster? if (isset ($foo)) OR if ($foo==true)

delphi - 找出Delphi ClassType是否继承自其他ClassType?

python - 参数的子类初始化