muduo-学习笔记(一)Timestamp部分

本文解析了Timestamp类的定义和实现,包括构造函数、时间戳获取、时间格式化输出等功能,并通过示例展示了如何使用该类进行时间计算。

Timestamp.h头文件,定义了Timestamp类中的相关函数和变量

#ifndef MUDUO_BASE_TIMESTAMP_H  //预定义
#define MUDUO_BASE_TIMESTAMP_H

#include <muduo/base/copyable.h>  //头文件  copyable.h是一个空实现,仅为了做标识
#include <muduo/base/Types.h>    //基本类型的声明
#include <boost/operators.hpp>

namespace muduo
class Timestamp : public muduo::copyable,  //标识这个类是可以拷贝的
                  public boost::less_than_comparable<Timestamp>  //less_than_comparable来自于operator头文件,表示用户可以在自己的类里仅定义少量的操作符(在这里是<),就可方便地自动生成其他操作符(如>,<=,>=)重载
{
 public:
  Timestamp()
    : microSecondsSinceEpoch_(0)  //初始化参数microSecondsSinceEpoch_为0
  { }

  explicit Timestamp(int64_t microSecondsSinceEpoch);  //explicit防止类构造函数的隐式自动转换

  void swap(Timestamp& that)   //函数 交换两个值
  {    std::swap(microSecondsSinceEpoch_, that.microSecondsSinceEpoch_);  }

  string toString() const;   //按不同的两种格式输出时间
  string toFormattedString() const;

  bool valid() const { return microSecondsSinceEpoch_ > 0; }

  int64_t microSecondsSinceEpoch() const { return microSecondsSinceEpoch_; }  //返回时间
  time_t secondsSinceEpoch() const       //对时间进行一个动态转换
  { return static_cast<time_t>(microSecondsSinceEpoch_ / kMicroSecondsPerSecond); }

  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();}

inline double timeDifference(Timestamp high, Timestamp low)
{
  int64_t diff = high.microSecondsSinceEpoch() - low.microSecondsSinceEpoch();
  return static_cast<double>(diff) / Timestamp::kMicroSecondsPerSecond;
}

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文件定义了头文件中没有实现的函数

#include <muduo/base/Timestamp.h>

#include <sys/time.h>
#include <stdio.h>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#undef __STDC_FORMAT_MACROS

#include <boost/static_assert.hpp>

using namespace muduo;

BOOST_STATIC_ASSERT(sizeof(Timestamp) == sizeof(int64_t)); //BOOST_STATIC_ASSERT是编译期的断言,在编译的时候就可以断言出错误

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;
  snprintf(buf, sizeof(buf)-1, "%" PRId64 ".%06" PRId64 "", seconds, microseconds); //将后面一连串的值赋给buf
  return buf;
}

string Timestamp::toFormattedString() const
{
  char buf[32] = {0};
  time_t seconds = static_cast<time_t>(microSecondsSinceEpoch_ / kMicroSecondsPerSecond);
  int microseconds = static_cast<int>(microSecondsSinceEpoch_ % kMicroSecondsPerSecond);
  struct tm tm_time;
  gmtime_r(&seconds, &tm_time);

  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);
  int64_t seconds = tv.tv_sec;
  return Timestamp(seconds * kMicroSecondsPerSecond + tv.tv_usec);
}

Timestamp Timestamp::invalid()
{  return Timestamp();}

Types.h和copyable.h的代码如下

#ifndef MUDUO_BASE_TYPES_H
#define MUDUO_BASE_TYPES_H

#include <stdint.h>
#ifdef MUDUO_STD_STRING
#include <string>
#else  // !MUDUO_STD_STRING
#include <ext/vstring.h>
#include <ext/vstring_fwd.h>
#endif

namespace muduo
{
#ifdef MUDUO_STD_STRING
using std::string;
#else  // !MUDUO_STD_STRING
typedef __gnu_cxx::__sso_string string;
#endif

template<typename To, typename From>
inline To implicit_cast(From const &f) {
  return f;
}
template<typename To, typename From>     // use like this: down_cast<T*>(foo);
inline To down_cast(From* f) {                   // so we only accept pointers
  if (false) {
    implicit_cast<From*, To>(0);
  }

#if !defined(NDEBUG) && !defined(GOOGLE_PROTOBUF_NO_RTTI)
  assert(f == NULL || dynamic_cast<To>(f) != NULL);  // RTTI: debug mode only!
#endif
  return static_cast<To>(f);
}
}
#endif
#ifndef MUDUO_BASE_COPYABLE_H
#define MUDUO_BASE_COPYABLE_H
namespace muduo
{
class copyable
{
};
};
#endif  // MUDUO_BASE_COPYABLE_H

测试程序如下:

#include <muduo/base/Timestamp.h>
#include <vector>
#include <stdio.h>

using muduo::Timestamp;
//c_str()函数用于返回一个指向正规C字符串的指针, 内容与本string串相同,此处是将char buf转换为字符串
void passByConstReference(const Timestamp& x)  //传递引用
{  printf("%s\n", x.toString().c_str());}

void passByValue(Timestamp x)    //传递值
{  printf("%s\n", x.toString().c_str());}

void benchmark()
{
  const int kNumber = 1000*1000;
  std::vector<Timestamp> stamps;
  stamps.reserve(kNumber);
  for (int i = 0; i < kNumber; ++i)
  {    stamps.push_back(Timestamp::now());  }
  printf("%s\n", stamps.front().toString().c_str());
  printf("%s\n", stamps.back().toString().c_str());
  printf("%f\n", 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!\n");    }
    else if (inc < 100)
    {      ++increments[inc];    }
    else
    {      printf("big gap %d\n", static_cast<int>(inc));    }
  }

  for (int i = 0; i < 100; ++i)
  {    printf("%2d: %d\n", i, increments[i]);  }
}

int main()
{
  Timestamp now(Timestamp::now());  //  等价于Timestamp now = Timestamp::now();
  printf("%s\n", now.toString().c_str());  //输出当前时间
  passByValue(now);
  passByConstReference(now);
  benchmark();
}

这一部分是muduo/base用于时间计算相关的东西,十分基础,也是之后实现Connection超时的基础
(第一次认真写博客记录自己学习 希望可以继续坚持)

评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值