我正在尝试为一些 C++ 代码计时,但结果很奇怪。我编写了这个测试程序来尝试隔离正在发生的事情。谁能解释一下结果?这是在 Ubuntu 11.04 和 EC2 中高 CPU 实例上运行的(如果相关)
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
timespec startTime, currentTime;
long elapsed;
for (int i=0; i<5; i++) {
clock_gettime(CLOCK_REALTIME, &startTime);
sleep(1);
clock_gettime(CLOCK_REALTIME, ¤tTime);
elapsed = currentTime.tv_nsec - startTime.tv_nsec;
cout << elapsed << " nanoseconds elapsed" << endl;
cout << "1000000000 expected" << endl;
}
return 0;
}
输出:
109044 nanoseconds elapsed
1000000000 expected
133713 nanoseconds elapsed
1000000000 expected
197287 nanoseconds elapsed
1000000000 expected
143396 nanoseconds elapsed
1000000000 expected
111871 nanoseconds elapsed
1000000000 expected