一、struct timeval結構體struct timeval結構體在time.h中的定義為:
struct timeval{__time_t tv_sec; /* Seconds. */__suseconds_t tv_usec; /* Microseconds. */};
其中,tv_sec為Epoch到建立struct timeval時的秒數,tv_usec為微秒數,即秒後面的零頭。比如當前我寫博文時的tv_sec為1244770435,tv_usec為442388,即目前時間距Epoch時間1244770435秒,442388微秒。需要注意的是,因為迴圈過程,建立結構體變數等過程需消耗部分時間,我們作下面的運算時會得到如下結果:
#include <sys/time.h>#include <stdio.h> intmain(void){ int i; struct timeval tv; for(i = 0; i < 4; i++){ gettimeofday(&tv, NULL); printf("%d\t%d\n", tv.tv_usec, tv.tv_sec); sleep(1); } return 0;}
3296121314851429329782131485143032991113148514313300361314851432
前面為微秒數,後面為秒數,可以看出,在這個簡單運算中,只能精確到小數點後面一到兩位,或者可以看出,每進行一次迴圈,均需花費0.005秒的時間,用這個程式來作計時器顯然是不行的,除非精確計算產生的代碼消耗時間。
二、gettimeofday()函數原型:
/* Get the current time of day and timezone information, putting it into *TV and *TZ. If TZ is NULL, *TZ is not filled. Returns 0 on success, -1 on errors. NOTE: This form of timezone information is obsolete. Use the functions and variables declared in <time.h> instead. */extern int gettimeofday (struct timeval *__restrict __tv, __timezone_ptr_t __tz) __THROW __nonnull ((1));
gettimeofday()功能是得到目前時間和時區,分別寫到tv和tz中,如果tz為NULL則不向tz寫入。
三、測試
#include <stdio.h>#include <sys/time.h> int main(){ struct timeval start, end; gettimeofday( &start, NULL ); sleep(3); gettimeofday( &end, NULL ); int timeuse = 1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec; printf("time: %d us\n", timeuse); return 0;}
上一篇:Linux下的段錯誤(Segmentation fault)產生的原因及調試方法(經典)
下一篇:位元組碼問題--wchar和char的區別以及wchar和char之間的相互轉換字元編碼轉換等方法及函數介紹