全球时间成本与本地时间成本总和-“ for”循环

问题描述 投票:0回答:1

表面上看起来很愚蠢,我想知道在调和for循环的时间成本时是否存在陷阱

  • for循环外部的时间点开始(globalexternal时间成本)
  • 或者,从时间点进入循环内部并被累计考虑(本地内部时间成本)?

下面的示例说明了我很难获得两个相等的度量:

#include <iostream>
#include <vector> // std::vector
#include <ctime> // clock(), ..

int main(){
  clock_t clockStartLoop;
  double timeInternal(0)// the time cost of the loop, summing all time costs of commands within the "for" loop
    , timeExternal // time cost of the loop, as measured outside the boundaries of "for" loop
    ;
  std::vector<int> vecInt; // will be [0,1,..,10000] after the loop below
  clock_t costExternal(clock());
  for(int i=0;i<10000;i++){
    clockStartLoop = clock();
    vecInt.push_back(i);
    timeInternal += clock() - clockStartLoop; // incrementing internal time cost
  }
  timeInternal /= CLOCKS_PER_SEC;
  timeExternal = (clock() - costExternal)/(double)CLOCKS_PER_SEC;

  std::cout << "timeExternal = "<< timeExternal << " s ";
  std::cout << "vs timeInternal = " << timeInternal << std::endl;
  std::cout << "We have a ratio of " << timeExternal/timeInternal << " between the two.." << std::endl;
}

例如,我通常得到大约2的比率作为输出

timeExternal = 0.008407 s vs timeInternal = 0.004287两者之比为1.96105。

,而我希望比率接近1。

  • 仅是因为循环中有操作[[internal,这些操作不是由clock()差来衡量的(例如递增timeInternal)? i++中的for(..)操作在外部测量中是否可以忽略不计,并且也可以解释与内部测量的区别?
  • 我实际上是在处理一个更复杂的代码,我想在一个循环中隔离时间成本,请确保我考虑的所有时间片都构成一个完整的饼图(直到现在我还没有实现。)。非常感谢

表面上看起来很愚蠢,我想知道在调和for循环的时间成本时是否存在陷阱,从for循环之外的时间点开始测量(全局...

c++ performance time
1个回答
1
投票
timeExternal = 0.008407 s vs timeInternal = 0.004287我们在两者之间的比率为1.96105。
© www.soinside.com 2019 - 2024. All rights reserved.