假设你有一个函数,你调用它很多次,每次函数返回一个大对象。我使用返回 void
的仿函数优化了问题,并将返回值存储在公共(public)成员中:
#include <vector>
const int N = 100;
std::vector<double> fun(const std::vector<double> & v, const int n)
{
std::vector<double> output = v;
output[n] *= output[n];
return output;
}
class F
{
public:
F() : output(N) {};
std::vector<double> output;
void operator()(const std::vector<double> & v, const int n)
{
output = v;
output[n] *= n;
}
};
int main()
{
std::vector<double> start(N,10.);
std::vector<double> end(N);
double a;
// first solution
for (unsigned long int i = 0; i != 10000000; ++i)
a = fun(start, 2)[3];
// second solution
F f;
for (unsigned long int i = 0; i != 10000000; ++i)
{
f(start, 2);
a = f.output[3];
}
}
是的,我可以使用内联或以其他方式优化这个问题,但在这里我想强调这个问题:使用仿函数我只声明和构造输出变量 output
一次,使用我每次调用时都会执行的功能。第二种解决方案比使用 g++ -O1
或 g++ -O2
的第一种解决方案快两倍。您怎么看,这是一个丑陋的优化吗?
编辑:
明确我的目标。我必须评估函数 >10M 次,但我只需要几次随机输出。重要的是输入没有改变,事实上我将它声明为一个 const 引用。在此示例中,输入始终相同,但在现实世界中,输入会发生变化,并且它是函数先前输出的函数。
最佳答案
更常见的场景是在函数外创建保留足够大的对象,并通过指针或引用将大对象传递给函数。您可以在多次调用您的函数时重用该对象。因此,您可以减少持续的内存分配。
关于c++ - 使用类和公共(public)成员优化输出值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2883472/