考虑一下:
#include <time.h>
#include <unistd.h>
#include <iostream>
using namespace std;
const int times = 1000;
const int N = 100000;
void run() {
for (int j = 0; j < N; j++) {
}
}
int main() {
clock_t main_start = clock();
for (int i = 0; i < times; i++) {
clock_t start = clock();
run();
cout << "cost: " << (clock() - start) / 1000.0 << " ms." << endl;
//usleep(1000);
}
cout << "total cost: " << (clock() - main_start) / 1000.0 << " ms." << endl;
}
下面是示例代码。在定时循环的前26次迭代中,run
函数的开销约为0.4 ms,但随后开销降至0.2 ms。
当取消 usleep
注释时,所有运行的延迟循环需要0.4 ms,从不加速。为什么?
代码是用 g++ -O0
编译的(没有优化) ,所以延迟循环没有被优化掉。它运行在 Intel (R) Core (TM) I3-3220 CPU@3.30 GHz 上,配有3.13.0-32-general Ubuntu 14.04.1 LTS (Trusty Tahr)。