Linux時間函數之gettimeofday()函數之使用方法

來源:互聯網
上載者:User

一.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()函數所使用的時間

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.