首页 > 代码库 > linux@64 获取时间的性能评估

linux@64 获取时间的性能评估

听人说gettimeofday 在64bit下有缓存,速度很快,测试下了,感觉不对啊。。

 

#include <time.h>#include <sys/time.h>#include <stdio.h>#include <stdint.h>int foo(int i){    return i;}const int64_t MAX_COUNT = 100000*1000;struct TimerEval {  TimerEval(const char* module)  {      start_time_ = time(NULL);      module_ = module;  }  ~TimerEval()  {      time_t end_time = time(NULL);      printf("%s\telapse : %d sec\n", module_,            (end_time - start_time_));  }  time_t start_time_;  const char* module_;};int main(){    struct timeval tpTmp;    printf("repeat %d times, test result is : \n", MAX_COUNT);    {        TimerEval eval("call fun");        for (int i=0; i<MAX_COUNT; ++i)            foo(i);    }    {        TimerEval eval("call time");        for (int i=0; i<MAX_COUNT; ++i)            time(NULL);;    }    {        TimerEval eval("call gettimeofday");        for (int i=0; i<MAX_COUNT; ++i)            gettimeofday(&tpTmp, NULL);;    }    {        TimerEval eval("call clock_gettime");        struct timespec tp;        for (int i=0; i<MAX_COUNT; ++i)            clock_gettime(CLOCK_REALTIME, &tp);    }    return 0;}

测试结果

repeat 100000000 times, test result is :
call fun    elapse : 1 sec
call time    elapse : 1 sec
call gettimeofday    elapse : 7 sec
call clock_gettime    elapse : 15 sec

编译参数

 g++ timer_benchmarck.cc -m64 -lrt

 

貌似事实可能不是这样,求教于大家,可能是什么原因。

如果说time只是在gettimeofday的基础上封装了一层,那怎么time会比gettimeofday还快,不科学啊!

/* 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;}

 

linux@64 获取时间的性能评估