我正在开发一个很大程度上基于数学(sin、cos、sqrt 等)的应用程序。 这些函数需要一些时间来运行,但精度很高。
我的一些客户不需要那么高的精度,但他们需要它尽可能快。
所以我有我的 Sin 函数,它是一个简单的数组(在程序开始运行之前创建),它取 0 到 360 之间的度数并返回它的 sin
(假设数组有360 值)。
我想创建一个界面:
interface MyMath
{
double PreciseSin(double x);
double PreciseCos(double x);
}
它将被继承
- “精确数学”实现将调用正常的 sin、cos 函数。
- “快速数学”将使用我之前解释过的数组技巧。
我的代码将使用“mymath”类型的变量来进行计算,并且在开始时将使用 preciseMath 或 fastMath 对其进行初始化。
最后我的问题是:
- 如果调用一个调用“Math.sin”而不是直接调用它的虚函数,我将在时间上付出多少代价?
- 编译器是否能够优化它并理解如果我用 PriciseMath 初始化 MyMath 我只想调用正常的 Sin 和 Cos 函数?
- 我能否更改我的设计以帮助编译器理解和优化我的代码?
最佳答案
很可能你的 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/