感谢" Ry - ",这可能是Empty loop is slower than a non-empty one in C的重复
我写了以下c ++代码:
#include <iostream>
#include <ctime>
void step() {
return;
}
void loop(int n) {
for (int i = 0; i < n; i++) {
step();
}
return;
}
int main(int argc, char** argv) {
clock_t tic = clock();
loop(int(1e9));
clock_t toc = clock();
std::cout << "elapsed in " << double(toc-tic)/CLOCKS_PER_SEC << " " << "seconds" << std::endl;
return 0;
}
然后我用-O0标志编译它。打印输出
elapsed in 1.23771 seconds
如果我删除&#34;步骤&#34;功能,留空循环,打印输出
elapsed in 2.72871 seconds
很奇怪看到一个空循环比一个循环慢,#34;什么都不做&#34;。有谁知道这里发生了什么?