1.簡介:
在C語言中可以使用函數gettimeofday()函數來得到精確時間。它的精度可以達到微妙,是C標准庫的函數。
2.函數原型:
#include<sys/time.h> int gettimeofday(struct timeval*tv,struct timezone *tz )
3.說明:
gettimeofday()會把目前的時間用tv 結構體返回,當地時區的信息則放到tz所指的結構中
4.結構體:
1. timeval 結構體定義:
struct timeval{ long tv_sec; /*秒*/ long tv_usec; /*微妙*/ };
2. timezone 結構定義:
struct timezone{ int tz_minuteswest;/*和greenwich 時間差了多少分鍾*/ int tz_dsttime; /*type of DST correction*/ }
3>在gettimeofday()函數中tv或者tz都可以為空。如果為空則就不返回其對應的結構體。
4>函數執行成功后返回0,失敗后返回-1,錯誤代碼存於errno中。
5.程序實例:
#include<stdio.h> #include<sys/time.h> #include<unistd.h> void hello_world(void) { printf("Hello world!!!!\r\n"); } int main(void) { struct timeval tv_begin,tv_end; gettimeofday(&tv_begin,NULL); hello_world(); gettimeofday(&tv_end,NULL); printf(“tv_begin_sec:%d\n”,tv_begin.tv_sec); printf(“tv_begin_usec:%d\n”,tv_begin.tv_usec); printf(“tv_end_sec:%d\n”,tv_end.tv_sec); printf(“tv_end_usec:%d\n”,tv_end.tv_usec); return 0; }
說明:在使用gettimeofday()函數時,第二個參數一般都為空,因為我們一般都只是為了獲得當前時間,而不用獲得timezone的數值。