C語言 利用gettimeofday()時間差計算

利用gettimeofday()函數可以獲取系統時間,其中,比較重要的結構體爲

           struct timeval {
               time_t      tv_sec;     /* 秒(seconds) */
               suseconds_t tv_usec;    /* 微秒(microseconds) */
           };

具體函數使用方法可以參考man手冊,下面是網上收集的一個不錯的例子。

#include <sys/time.h>
#include <time.h>
#include <stdio.h>
#include <string.h>

double difftimeval(const struct timeval *start, const struct timeval *end)
{
        double d;
        time_t s;
        suseconds_t u;

        s = start->tv_sec - end->tv_sec;
        u = start->tv_usec - end->tv_usec;
        //if (u < 0)
        //        --s;

        d = s;
        d *= 1000000.0;//1 秒 = 10^6 微秒
        d += u;

        return d;
}

char *strftimeval(const struct timeval *tv, char *buf)
{
        struct tm      tm;
        size_t         len = 28;

        localtime_r(&tv->tv_sec, &tm);
        strftime(buf, len, "%Y-%m-%d %H:%M:%S", &tm);
        len = strlen(buf);
        sprintf(buf + len, ".%06.6d", (int)(tv->tv_usec));
        return buf;
}

int main(int argc, char *argv[])
{
        char buf[28];
        struct timeval start,end;

        gettimeofday(&start, NULL);//獲取開始時間
        //do sth ...
        usleep(100);
        gettimeofday(&end, NULL);  //獲取結束時間

        printf("%s\n", strftimeval(&start, buf));
        printf("%s\n", strftimeval(&end, buf));
        printf("%.0f\n", difftimeval(&end, &start));
        return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章