Linux時間函數之gettimeofday()函數之使用方法
一.gettimeofday()函數的使用方法:
1.簡介:
在C語言中可以使用函數gettimeofday()函數來得到時間。它的精度可以達到微妙
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>
int main()
{
struct timeval tv;
struct timezone tz;
gettimeofday(&tv,&tz);
printf(“tv_sec:%d\n”,tv.tv_sec);
printf(“tv_usec:%d\n”,tv.tv_usec);
printf(“tz_minuteswest:%d\n”,tz.tz_minuteswest);
printf(“tz_dsttime:%d\n”,tz.tz_dsttime);
}
說明:在使用gettimeofday()函數時,第二個參數一般都為空,因為我們一般都隻是為了獲得當前時間,而不用獲得timezone的數值
二.gettimeofday()函數的一個常用方法
在測試程序時,往往需要了解程序執行所需的時間,在Linux中可以使用函數gettimeofday來得到時間.
1.程序實例:
測試調用delya()函數所需執行的時間(單位為微妙)
#include<stdio.h>
#include<sys/time.h>
#include<unistd.h>
int delay(int time)
{
int i,j;
for(i =0;i<time;i++)
for(j=0;j<5000;j++)
;
}
int main()
{
struct timeval start;
struct timeval end;
unsigned long diff;
gettimeofday(&start,NULL);
delay(10);
gettimeofday(&end,NULL);
diff = 1000000 * (end.tv_sec-start.tv_sec)+ end.tv_usec-start.tv_usec;
printf(“thedifference is %ld\n”,diff);
return 0;
}
說明:
使用該方法就可以檢測出調用delay()函數所使用的時間
最後更新:2017-04-02 00:06:51