time和gettimeofday的性能差異

    兩個都是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 sec

time():
elapse : 0.29195 sec

gettimeofday():
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_t
time (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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章