()函數的使用方法 1.簡介:
在C語言中可以使用函數()函數來得到精確時間。它的精度可以達到微妙,是C標準庫的函數。
2.函數原型:
#includeint gettimeofday(struct timeval*tv,struct timezone *tz )
3.說明:
()會把目前的時間用tv 結構體返回c語言獲取當前時間戳,當地時區的信息則放到tz所指的結構中
4.結構體:
1. 結構體定義:
struct timeval{ long tv_sec; /*秒*/ long tv_usec; /*微妙*/};
2. 結構定義:
struct timezone{ int tz_minuteswest;/*和greenwich 時間差了多少分鐘*/ int tz_dsttime; /*type of DST correction*/ }
3>在()函數中tv或者tz都可以為空。如果為空則就不返回其對應的結構體。
4>函數執行成功后返回0,失敗后返回-1,錯誤代碼存于errno中。
5.程序實例:
#include#include #include 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; }
//統計耗時,單位ms
int times = (_sec*1000+_usec/1000) - (_sec*1000+_usec/1000);
說明:在使用()函數時c語言獲取當前時間戳,第二個參數一般都為空,因為我們一般都只是為了獲得當前時間,而不用獲得的數值
time函數
函數聲明: time ( *);
其中為time.h定義的結構體,一般為長整型
time函數返回的為unix時間戳,即從1970年1月1日(UTC/GMT的午夜)開始所經過的秒數,不考慮閏秒。
如果參數非空,會存儲相同值到指向的內存中。
函數,返回年月日時分秒
函數聲明: tm * (const *);
tm為一個結構體,包含了年月日時分秒等信息
#include
#include
int main ()
{
time_t t;
struct tm * lt;
time (&t);//獲取Unix時間戳。
lt = localtime (&t);//轉為時間結構。
printf ( "%d/%d/%d %d:%d:%d\n",lt->tm_year+1900, lt->tm_mon+1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec);//輸出結果
return 0;
}