4
我想花時間使用一些C++代碼,但是我得到的結果很奇怪。我寫了這個測試程序來試圖隔離發生了什麼。任何人都可以解釋結果嗎?這是如果這是有關在Ubuntu 11.04和EC2中高CPU實例運行clock_gettime性能不一致
#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
另一種方法是:將'1000000000 expected'行改爲'0 expected'。 :) – sarnold 2012-07-06 01:41:57
@sarnold:嘿,我想它確實測量了'sleep(1)'調用的開銷,並且進入了'clock_gettime()'調用的一半:-)。 – jxh 2012-07-06 01:44:53