考虑:
#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毫秒,但之后成本降低到0.2毫秒。
取消注释usleep
时,延迟循环对所有运行需要0.4毫秒,从未加速。为什么?
该代码使用g++ -O0
(无优化)编译,因此延迟循环不会被优化掉。它在Intel(R) Core(TM) i3-3220 CPU @ 3.30 GHz上运行,使用3.13.0-32-generic Ubuntu 14.04.1 LTS (Trusty Tahr)。
usleep()
的结果,因为它可能会被中断或者由于参数无效而不起作用。这将使任何时间计算变得不可靠。 - John3136gcc -O2
或(由于您的代码是C++)g++ -O2
进行编译。 - Basile Starynkevitchusleep
在时间窗口之外。 - Peter Cordes