【发布时间】:2017-04-01 17:25:07
【问题描述】:
我想为我的插入排序计时。如果我有这样的代码,它可以工作,但它会为循环中的每种排序打印一次(因为它在循环中):
clock_t start;
double duration;
start = clock();
int j, temp;
for (int i = 0; i < NumberOfLines; i++) {
j = i;
while (j > 0 && arr[j - 1] < arr[j]) {
temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
j--;
}
duration = (clock() - start) / (double)CLOCKS_PER_SEC;
cout<<"Sorting took: "<< duration<<" seconds"<<'\n';
}
duration = (std::clock() - start) / (double)CLOCKS_PER_SEC;
cout << "Please Work: " << duration << " seconds" << '\n';
但如果我在循环内注释cout,它会返回 0 所用时间:
duration = (clock() - start) / (double)CLOCKS_PER_SEC;
//cout<<"Sorting took: "<< duration<<" seconds"<<'\n';
}
duration = (std::clock() - start) / (double)CLOCKS_PER_SEC;
cout << "Please Work: " << duration << " seconds" << '\n';
为什么?
【问题讨论】:
-
优化。循环后打印排序数组以防止它。
-
我敢打赌,因为您的循环的执行时间远远少于捕获时间所需的时间,最重要的是发射到连接到控制台或文件的流。而且通常时钟的粒度并不能很好地捕捉到一个简单循环的几百次迭代。
-
@yurikilochek 是的,这可能是我必须做的。
-
@LaurentG 我不确定,因为如果我在循环中打印时间(上面的第一个代码块)它会打印时间。
-
This question 可能是相关的。