C++函数调用非常慢

Chr*_*oph 2 c++ performance function call

我编写了一个递归的Branch&Cut算法,现在正试图加快执行速度.我注意到了一些非常好奇的东西:有一次我调用一个函数来计算一些向量向量.使用clock(),我测量了在调用它的文件中以及在函数本身中花费的时间.可视化:

tic
foo(args);
time1 = toc
Run Code Online (Sandbox Code Playgroud)

void foo(args) {
  tic
  //do stuff
  time2 = toc
}
Run Code Online (Sandbox Code Playgroud)

我的问题是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 )
Run Code Online (Sandbox Code Playgroud)

我通过引用传递所有向量以避免复制它们,但也许我错过了什么?或者通常使用那么多参数调用函数通常很慢?此外,进入该功能使用的时间比退出该功能的时间长,这可能很重要.

如果您需要更多信息,请告诉我.谢谢和欢呼,Christoph


提升Graph对象是​​问题,感谢发现它:)运行时间降低了10倍,完美!

izo*_*ica 7

虽然没有那么好的设计将许多参数传递给函数但不会显着降低速度(假设你通过refference传递所有东西).但是我注意到你特别将副本传递给某些东西Graph F,这似乎是一件很重要的事情.


Luc*_*ore 5

只是一个猜测,但是:

   time2 = toc
}
Run Code Online (Sandbox Code Playgroud)

我猜的罪魁祸首是}.说你有类似的东西:

void foo(args) {
  tic
  SomeReallyExpensiveObject x;
  time2 = toc
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,你没有计时破坏.如果在自动存储中有大量载体,它们的破坏可能需要很长时间.

试试这个实验:

void foo(args) {
  tic
  {
     //do stuff
  }
  time2 = toc
}
Run Code Online (Sandbox Code Playgroud)

如果测量的时间越来越近,那就是问题所在.