【发布时间】:2019-10-25 14:34:07
【问题描述】:
虽然看起来很愚蠢,但我想知道在尝试协调 for 循环的时间成本时是否可能存在缺陷
- 来自
for循环之外的时间点(全局或外部时间成本) - 或者,从循环内部的时间点开始,并被累积考虑(本地或内部时间成本)?
下面的例子说明了我在获得两个相等的测量值时遇到的困难:
#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)? -
for(..)中的i++操作能否在外部测量中不可忽略,并解释与内部测量的区别?
我实际上正在处理一个更复杂的代码,我想在一个循环中隔离时间成本,确保我考虑的所有时间片确实构成了一个完整的馅饼(直到现在我从未实现过......) .非常感谢
【问题讨论】:
-
很可能大部分时间都花在
clock()调用本身上,然后您正在测量 1 次 clock() 调用与 2 次的累积时间。为什么不使用适当的 C++ 分析器? -
因为我在适当的分析器方面没有经验(还没有?)。也许是时候获得一些了,谢谢。
-
我建议你比较一下这段代码的两个版本:一个只有外部时间,一个只有内部时间的总和
标签: c++ performance time