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

你可能感兴趣的:(time和gettimeofday的性能差异)