• muduo网络库源码学习————Timestamp.cc


    今天开始学习陈硕先生的muduo网络库,moduo网络库得到很多好评,陈硕先生自己也说核心代码不超过5000行,所以我觉得有必要拿过来好好学习下,学习的时候在源码上面添加一些自己的注释,方便日后理解,首先看看UTC时间戳,源码目录为base文件夹:
    Timestamp.h

    //UTC时间戳 
    //类声明文件
    #ifndef MUDUO_BASE_TIMESTAMP_H
    #define MUDUO_BASE_TIMESTAMP_H
    
    #include <muduo/base/copyable.h>
    #include <muduo/base/Types.h>
    
    #include <boost/operators.hpp>
    
    namespace muduo
    {
    // Time stamp in UTC, in microseconds resolution.
    //时间起始点是1970 1月1号0:0:0
    // This class is immutable.
    // It's recommended to pass it by value, since it's passed in register on x64.
    //继承两个类
    //muduo::copyable空基类,标识类,值类型
    //boost::less_than_comparable<Timestamp>要求实现< 号运算符
    //可自动实现>,<=,>=
    //这是一种模板语言编程思想
    class Timestamp : public muduo::copyable, public boost::less_than_comparable<Timestamp>
    {
     public:
      //
      // Constucts an invalid Timestamp.
      //
      Timestamp(): microSecondsSinceEpoch_(0)
      {
      }
      // Constucts a Timestamp at specific time
      // @param microSecondsSinceEpoch
      explicit Timestamp(int64_t microSecondsSinceEpoch);
    //两个时间戳进行交换
      void swap(Timestamp& that)
      {
        std::swap(microSecondsSinceEpoch_, that.microSecondsSinceEpoch_);
      }
    
      // default copy/assignment/dtor are Okay
      string toString() const;
      string toFormattedString() const;
      bool valid() const { return microSecondsSinceEpoch_ > 0; }
      // for internal usage.
      int64_t microSecondsSinceEpoch() const { return microSecondsSinceEpoch_; }
      time_t secondsSinceEpoch() const
      { return static_cast<time_t>(microSecondsSinceEpoch_ / kMicroSecondsPerSecond); }
     //Get time of now.
      //获取当前时间
      static Timestamp now();
      //获取一个失效的时间,看第一个构造函数那里
      static Timestamp invalid();
     static const int kMicroSecondsPerSecond = 1000 * 1000;
     private:
      int64_t microSecondsSinceEpoch_;
    };
    //其他的号会自己实现
    inline bool operator<(Timestamp lhs, Timestamp rhs)
    {
      return lhs.microSecondsSinceEpoch() < rhs.microSecondsSinceEpoch();
    }
    inline bool operator==(Timestamp lhs, Timestamp rhs)
    {
      return lhs.microSecondsSinceEpoch() == rhs.microSecondsSinceEpoch();
    }
    //Gets time difference of two timestamps, result in seconds.
    //
    // @param high, low
    // @return (high-low) in seconds
    // @c double has 52-bit precision, enough for one-microseciond
    // resolution for next 100 years.
    //用于计算两个时间的差
    inline double timeDifference(Timestamp high, Timestamp low)
    {
      int64_t diff = high.microSecondsSinceEpoch() - low.microSecondsSinceEpoch();//这里得到的是微秒
      return static_cast<double>(diff) / Timestamp::kMicroSecondsPerSecond;//转化为秒数
      //kMicroSecondsPerSecond为上面定义的一个常量
    }
    // Add @c seconds to given timestamp.
    // @return timestamp+seconds as Timestamp
    //在时间的基础上增加多少秒
    inline Timestamp addTime(Timestamp timestamp, double seconds)
    {
      int64_t delta = static_cast<int64_t>(seconds * Timestamp::kMicroSecondsPerSecond);//先把秒转化为微秒
      return Timestamp(timestamp.microSecondsSinceEpoch() + delta);//构造一个新的对象加上新的微秒
    }
    
    }
    #endif  // MUDUO_BASE_TIMESTAMP_H
    

    Timestamp.cc

    //UTC 时间戳类实现文件
    #include <muduo/base/Timestamp.h>
    
    #include <sys/time.h>
    #include <stdio.h>
    #define __STDC_FORMAT_MACROS
    #include <inttypes.h>//PRId64所在的头文件,在C++当中需要定义上面那个宏才可以使用PRId64
    #undef __STDC_FORMAT_MACROS
    
    #include <boost/static_assert.hpp>
    
    using namespace muduo;
    //编译时断言,在编译的时候检查 该条件是否满足
    BOOST_STATIC_ASSERT(sizeof(Timestamp) == sizeof(int64_t));
    //构造函数初始化赋值
    Timestamp::Timestamp(int64_t microseconds): microSecondsSinceEpoch_(microseconds)
    {
    }
    
    string Timestamp::toString() const
    {
      char buf[32] = {0};
      int64_t seconds = microSecondsSinceEpoch_ / kMicroSecondsPerSecond;//得到秒数
      int64_t microseconds = microSecondsSinceEpoch_ % kMicroSecondsPerSecond;//得到微秒数
      //PRId64是为了实现跨平台,32位机器表示64位是lld,64位机器表示64位是ld
      snprintf(buf, sizeof(buf)-1, "%" PRId64 ".%06" PRId64 "", seconds, microseconds);
      return buf;
    }
    //把时间转化为一个格式化的字符串
    string Timestamp::toFormattedString() const
    {
      char buf[32] = {0};
      time_t seconds = static_cast<time_t>(microSecondsSinceEpoch_ / kMicroSecondsPerSecond);//得到距离1970年那个时间的秒数
      int microseconds = static_cast<int>(microSecondsSinceEpoch_ % kMicroSecondsPerSecond);//得到距离1970年那个时间的微秒数
      struct tm tm_time;
      gmtime_r(&seconds, &tm_time);//gmtime_r将一个秒数转化为结构体
    //将时间结构体里面的时间取出来放进buf里面
      snprintf(buf, sizeof(buf), "%4d%02d%02d %02d:%02d:%02d.%06d", tm_time.tm_year + 1900, tm_time.tm_mon + 1, tm_time.tm_mday,
        tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec,microseconds);
      return buf;
    }
    //获取当前的时间
    Timestamp Timestamp::now()
    {
      struct timeval tv;
      gettimeofday(&tv, NULL);//这里返回一个timeval的结构体,第二个参数是一个时区,这里我们不需要返回
      int64_t seconds = tv.tv_sec;
      return Timestamp(seconds * kMicroSecondsPerSecond + tv.tv_usec);//得到的是距离19700101的微秒数的一个新的对象
    }
    //获取一个失效的时间
    Timestamp Timestamp::invalid()
    {
      return Timestamp();
    }
    
    

    测试文件在base/tests下面的Timestamp_unittest.cc
    Timestamp_unittest.cc

    //UTC 时间戳的测试代码
    #include <muduo/base/Timestamp.h>
    #include <vector>
    #include <stdio.h>
    
    using muduo::Timestamp;
    
    void passByConstReference(const Timestamp& x)
    {
      printf("%s
    ", x.toString().c_str());
    }
    
    void passByValue(Timestamp x)
    {
      printf("%s
    ", x.toString().c_str());
    }
    
    void benchmark()
    {//const常量前面加个K是谷歌推荐的编码规范
      const int kNumber = 1000*1000;
    
      std::vector<Timestamp> stamps;
      stamps.reserve(kNumber);//先预留kNumber个对象的空间
      for (int i = 0; i < kNumber; ++i)
      {//插入100w个now,目的是为了计算执行gettimeofday的时间
        stamps.push_back(Timestamp::now());
      }
      //c_str() 以 char* 形式传回 string 内含字符串
      printf("%s
    ", stamps.front().toString().c_str());//打印第一个插入的时间
      printf("%s
    ", stamps.back().toString().c_str());//打印最后一个插入的时间
      printf("%f
    ", timeDifference(stamps.back(), stamps.front()));//计算时间差
    
      int increments[100] = { 0 };
      int64_t start = stamps.front().microSecondsSinceEpoch();
      for (int i = 1; i < kNumber; ++i)
      {
        int64_t next = stamps[i].microSecondsSinceEpoch();
        int64_t inc = next - start;
        start = next;
        if (inc < 0)
        {
          printf("reverse!
    ");
        }
        else if (inc < 100)//时间差小于100
        {
          ++increments[inc];
        }
        else
        {
          printf("big gap %d
    ", static_cast<int>(inc));
        }
      }
    
      for (int i = 0; i < 100; ++i)
      {
        printf("%2d: %d
    ", i, increments[i]);
      }
    }
    
    int main()
    {//构造一个时间戳对象,拷贝构造给now对象
      Timestamp now(Timestamp::now());
      printf("%s
    ", now.toString().c_str());//输出当前时间的toString,格式秒,微秒
      passByValue(now);
      passByConstReference(now);
      benchmark();//一个度量时间的函数
    }
    
    

    拿出来单独编译,运行可得到如下的结果:
    这里写图片描述

  • 相关阅读:
    跨浏览器的事件处理程序(javascript高级程序设计第二版第十二章)
    json
    html5 本地存储Web Storage
    sicily 6497. 字符统计
    sicily 6415. linear correlation
    sicily 1154. Easy sort
    sicily 6496. 二维数组
    sicily 6423. 反向输出数字
    sicily 1636. show me the money
    sicily 1324. Score
  • 原文地址:https://www.cnblogs.com/sigma0-/p/12630490.html
Copyright © 2020-2023  润新知