我已经编写了递归 Branch&Cut 算法,现在正试图加快执行速度。不过,我注意到了一些非常奇怪的事情:有一次我调用了一个函数来计算一些 vector 的 vector 。使用 clock(),我测量了在调用该函数的文件中以及函数本身中花费在该函数上的时间。可视化:
tic
foo(args);
time1 = toc
和
void foo(args) {
tic
//do stuff
time2 = toc
}
我的问题是 time1 大约是 time2 的 3 倍,这对我来说毫无意义。实际函数有很多参数,如下所示:
void allcomb( std::vector<int> &Vin,
std::vector<int> &Vprev,
Graph F,
int t,
const int n,
const int numofdests,
int Time_hor,
std::vector<int> &truckdest,
std::vector<int> &truck_dest_index,
std::vector<int> &descroflabel,
std::vector<int> &labelofdescr,
std::vector<std::vector<double> > &short_path_time,
std::vector<std::vector<double> > &short_path_fuel,
double eta,
std::vector<std::pair<int,int> >& next_hub,
std::vector<std::pair<double,double> >& distanceto_next_hub,
std::vector<std::vector<int> >& Choices )
我通过引用传递所有 vector 以避免复制它们,但也许我遗漏了什么?还是经常调用带有那么多参数的函数通常很慢? 此外,进入函数比退出函数花费更多的时间,也许这很重要。
如果您需要更多信息,请告诉我。 谢谢,干杯,克里斯托夫
boost Graph 对象是问题所在,感谢您发现它 :) 运行时间降低了 10 倍,完美!
最佳答案
虽然不是很好的设计,但将许多参数传递给函数不会显着降低速度(假设您通过引用传递所有内容)。但是,我注意到您将拷贝传递给某些东西,特别是 Graph F
,这似乎可能很大。
关于C++ 函数调用非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14605243/