struct timeval結構體 以及 gettimeofday()函數

來源:互聯網
上載者:User


一、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之間的相互轉換字元編碼轉換等方法及函數介紹
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.