表面上看起来很愚蠢,我想知道在调和for
循环的时间成本时是否存在陷阱
for
循环外部的时间点开始(global或external时间成本)下面的示例说明了我很难获得两个相等的度量:
#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。
timeInternal
)? i++
中的for(..)
操作在外部测量中是否可以忽略不计,并且也可以解释与内部测量的区别?表面上看起来很愚蠢,我想知道在调和for循环的时间成本时是否存在陷阱,从for循环之外的时间点开始测量(全局...
timeExternal = 0.008407 s vs timeInternal = 0.004287我们在两者之间的比率为1.96105。