muduo源码分析:Timestamp
timestamp.h:
#ifndef MUDUO_BASE_TIMESTAMP_H
#define MUDUO_BASE_TIMESTAMP_H
#include "copyable.h"
#include "Types.h"
//#include <concepts>
#include <boost/operators.hpp>
namespace muduo
{
///
/// Time stamp in UTC, in microseconds resolution.
// 以UTC为单位的时间截,分辨率为微妙
///
/// This class is immutable.
// 这个类是不可变的
/// It's recommended to pass it by value, since it's passed in register on x64
// 建议按值传递,因为它是在X64上的寄存器中传递的
///
//boost::equality_comparable:C++20 只要==操作符重载,自动实现!=操作符重载。
//boost::less_than_comparable:C++20 只要实现<操作符重载,自动实现>,<=,>=操作符重载
class Timestamp : public muduo::copyable,
public boost::equality_comparable<Timestamp>,
public boost::less_than_comparable<Timestamp>
{
public:
///
/// Constucts an invalid Timestamp.
// 构造无效的时间截
///成员变量microSecondsSinceEpoch_表示到1970-01-01 00:00:00 UTC的微秒数
Timestamp()
: microSecondsSinceEpoch_(0)
{
}
///
/// Constucts a Timestamp at specific time
// 在特定时间构建时间截
///
/// @param microSecondsSinceEpoch
explicit Timestamp(int64_t microSecondsSinceEpochArg)
: microSecondsSinceEpoch_(microSecondsSinceEpochArg)
{
}
//使用引用,避免复制大块数据
//库函数不知道如何交换自定义类型,需要自定义交换操作
void swap(Timestamp& that)
{
std::swap(microSecondsSinceEpoch_, that.microSecondsSinceEpoch_);
}
// default copy/assignment/dtor are Okay
// 默认拷贝/分配/析构
//将时间转换成string
string toString() const;
//将时间转换为指定格式
string toFormattedString(bool showMicroseconds = true) const;
// 判断Timestamp是否有效
bool valid() const { return microSecondsSinceEpoch_ > 0; }
// for internal usage.
// 用于内部使用
// 返回microSecondsSinceEpoch_
int64_t microSecondsSinceEpoch() const { return microSecondsSinceEpoch_; }
//返回秒数/微秒数
//kMicroSecondsPerSecond表示每秒所对应的微秒数
time_t secondsSinceEpoch() const
{ return static_cast<time_t>(microSecondsSinceEpoch_ / kMicroSecondsPerSecond); }
///
/// Get time of now.
///
//返回当前时间的Timestamp
static Timestamp now();
//返回一个无效的Timestamp
static Timestamp invalid()
{
return Timestamp();
}
static Timestamp fromUnixTime(time_t t)
{
return fromUnixTime(t, 0);
}
static Timestamp fromUnixTime(time_t t, int microseconds)
{
return Timestamp(static_cast<int64_t>(t) * kMicroSecondsPerSecond + microseconds);
}
//kMicroSecondsPerSecond表示每秒所对应的微秒数
static const int kMicroSecondsPerSecond = 1000 * 1000;
private:
//成员变量microSecondsSinceEpoch_表示到1970-01-01 00:00:00 UTC的微秒数
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-microsecond
/// 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;
}
///
/// Add @c seconds to given timestamp.
///
/// @return timestamp+seconds as Timestamp
///
//加时间到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.cpp:
#include "Timestamp.h"
#include <sys/time.h>
#include <stdio.h>
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>
//#include <boost/static_assert.hpp>
using namespace muduo;
//static_assert编译时断言
//assert是运行时断言
static_assert(sizeof(Timestamp) == sizeof(int64_t));
//以秒的形式输出Timestamp中时间,精确到微秒
string Timestamp::toString() const
{
char buf[32] = {0};
int64_t seconds = microSecondsSinceEpoch_ / kMicroSecondsPerSecond;
int64_t microseconds = microSecondsSinceEpoch_ % kMicroSecondsPerSecond;
//%06:宽度为6,不足左边补0
snprintf(buf, sizeof(buf)-1, "%" PRId64 ".%06" PRId64 "", seconds, microseconds);
return buf;
}
//将当前Timestamp时间对象格式化输出为年月日时分秒格式,如果选择了showMicroseconds,那么将精确到微秒
string Timestamp::toFormattedString(bool showMicroseconds) const
{
char buf[64] = {0};
time_t seconds = static_cast<time_t>(microSecondsSinceEpoch_ / kMicroSecondsPerSecond);
struct tm tm_time;
//struct tm *gmtime_r(const time_t *timep, struct tm *result);
//把time_t结构中的信息转换成真实世界所使用的时间日期,存储在tm_time结构中
gmtime_r(&seconds, &tm_time);
if (showMicroseconds)
{
int microseconds = static_cast<int>(microSecondsSinceEpoch_ % kMicroSecondsPerSecond);
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);
}
else
{
snprintf(buf, sizeof(buf), "%4d%02d%02d %02d:%02d:%02d",
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);
}
return buf;
}
// 获取当前时间,将当前时间转化为微秒并返回一个Timestamp对象
Timestamp Timestamp::now()
{
struct timeval tv;
gettimeofday(&tv, NULL);
int64_t seconds = tv.tv_sec;
return Timestamp(seconds * kMicroSecondsPerSecond + tv.tv_usec);
}
test:
#include "Timestamp.h"
#include <vector>
#include <stdio.h>
using muduo::Timestamp;
void passByConstReference(const Timestamp& x)
{
//c_str()函数返回一个指向正规C字符串的指针
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;
// 创建一个KNumber大小的stamps
std::vector<Timestamp> stamps;
stamps.reserve(kNumber);
//将kNumber个Timestamp放置到该向量中,时间为当前时间
for (int i = 0; i < kNumber; ++i)
{
stamps.push_back(Timestamp::now());
}
//打印第一个和最后一个Timestamp对象
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 main()
{
Timestamp now(Timestamp::now());//构造函数初始化一个Timestamp,时间为当前时间
printf("%s\n", now.toString().c_str());//打印当前时间微秒数
passByValue(now);//打印当前时间微秒数
passByConstReference(now);//打印当前时间微秒数
benchmark();
}