閱讀this article大約經過時間後,我寫了一個簡單的代碼來計算一個循環的執行時間:如何使用struct timeval來獲取執行時間?
#include <stdio.h>
#include <sys/time.h>
int main (int argc, char** argv) {
struct timeval, tvalBefore, tvalAfter;
gettimeofday (&tvalBefore, NULL);
int i =0;
while (i < 1000) {
i ++;
}
gettimeofday (&tvalAfter, NULL);
printf("Time in microseconds: %0.3f microseconds\n",
(float)(tvalAfter.tv_sec - tvalBefore.tv_sec)
)
return 0;
}
鐺編譯器給了我以下錯誤:
print_time.c:7:16: error: expected identifier or '('
struct timeval, *tvalBefore, *tvalAfter;
^
print_time.c:13:17: error: use of undeclared identifier 'tvalBefore'
gettimeofday (&tvalBefore, NULL);
^
print_time.c:19:17: error: use of undeclared identifier 'tvalAfter'
gettimeofday (&tvalAfter, NULL);
^
print_time.c:22:12: error: use of undeclared identifier 'tvalAfter'
(float)(tvalAfter.tv_sec - tvalBefore.tv_sec)
^
print_time.c:22:31: error: use of undeclared identifier 'tvalBefore'
(float)(tvalAfter.tv_sec - tvalBefore.tv_sec)
^
5 errors generated.
我不能找出我的代碼有什麼問題,有什麼想法?
取出,經過「timeval結構」 – LSerni
逗號不要使用gettimeofday的測量執行時間!閱讀此:http://blog.habets.pp.se/2010/09/gettimeofday-should-never-be-used-to-measure-time和此:http://stackoverflow.com/questions/12392278/getrusage -vs-clock-gettime-vs-clock-vs-gettimeofday/12480485#12480485 –
@ DouglasB.Staple感謝你讓我知道這個問題 – mko