zoukankan      html  css  js  c++  java
  • 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	elapse : %d sec
    ", module_,
                (end_time - start_time_));
      }
      time_t start_time_;
      const char* module_;
    };
    int main()
    {
        struct timeval tpTmp;
        printf("repeat %d times, test result is : 
    ", 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_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;
    }
  • 相关阅读:
    N!的位数
    c语言memset()函数
    通宵教室(ACM水题)
    欧拉函数+素数筛
    快速幂+大数取模
    观光浏览
    插入类排序(直接插入排序)
    showDoc使用方法
    $_POST与input('post.')区别
    “三日”面试官心得
  • 原文地址:https://www.cnblogs.com/westfly/p/4115171.html
Copyright © 2011-2022 走看看