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;
    }
  • 相关阅读:
    1.第一个java程序
    5.第三章 运算符和基本选择结构
    7.关系运算符
    4.第二章章末总结
    3.计算员工工资
    JAVA并发操作——Thread常见用法(Sleep,yield,后台线程)
    JAVA 对象序列化(一)——Serializable
    JAVA 线程中的异常捕获
    JAVA反射机制实例
    JAVA 对象序列化(二)——Externalizable
  • 原文地址:https://www.cnblogs.com/westfly/p/4115171.html
Copyright © 2011-2022 走看看