time和gettimeofday的效能差異

來源:互聯網
上載者:User

    兩個都是glibc擷取時間的函數,    gettimeofday支援返回微妙的精度, time返回秒的精度,  在效能上有差別嗎?

    基本上沒有效能差別, 因為time其實就是把gettimeofday封裝了一層. 但是測試過程中發現 time比gettimeofday效能好了一點點, 可能是time函數的介面形式簡單吧, 堆棧處理的快.

測試程式:

#include <time.h>#include "ctimer.h"int foo(int i){    return i;}const int MAX_COUNT = 1000*1000;int main(){    CMyTimer t;    struct timeval tpTmp;     printf("repeat %d times, test result is : \n", MAX_COUNT);    printf("\n");    {        t.Begin();        for (int i=0; i<MAX_COUNT; ++i)            foo(i);        printf("foo():\n");        printf("elapse : %5.5f sec\n", t.GetElapseTimeSec());         printf("\n");    }    {        t.Begin();        for (int i=0; i<MAX_COUNT; ++i)            time(NULL);;        printf("time():\n");        printf("elapse : %5.5f sec\n", t.GetElapseTimeSec());        printf("\n");    }    {        t.Begin();        for (int i=0; i<MAX_COUNT; ++i)            gettimeofday(&tpTmp, NULL);;        printf("gettimeofday():\n");        printf("elapse : %5.5f sec\n", t.GetElapseTimeSec());        printf("\n");    }    return 0;}

 

測試結果:

repeat 1000000 times, test result is : foo():elapse : 0.00564 sectime():elapse : 0.29195 secgettimeofday():elapse : 0.32929 sec

 

glibc time函數的實現: (可以看出是把gettimeofday封裝了一層)
代碼取自: glibc-2.17/sysdeps/posix/time.c

/* Return the current time as a `time_t' and also put it in *T if T is   not NULL.  Time is represented as seconds from Jan 1 00:00:00 1970.  */time_ttime (t)      time_t *t; {  struct timeval tv;   time_t result;  if (__gettimeofday (&tv, (struct timezone *) NULL))    result = (time_t) -1;                                                                                                         else    result = (time_t) tv.tv_sec;  if (t != NULL)    *t = result;  return result;}

 // 2013.06.21 號更新
增加對 clock_gettime函數的測試. 速度比gettimeofday慢一倍
    struct timespec tp;
    {
        t.Begin();
        for (int i=0; i<MAX_COUNT; ++i)
        {//clock_gettime(CLOCK_MONOTONIC, &tp);;
            clock_gettime(CLOCK_REALTIME, &tp);;
        }

        printf("clock_gettime():\n");
        printf("elapse : %5.5f sec\n", t.GetElapseTimeSec());
        printf("\n");

    }

結果如下:
foo():
elapse : 0.02448 sec

time():
elapse : 0.38708 sec

gettimeofday():
elapse : 0.47341 sec

clock_gettime():
elapse : 0.75391 sec

聯繫我們

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