一、Timestamp类
1、类图如下:
2、 知识点
(1) 这个类继承了 muduo::copyable, 以及 boost::less_than_comparable.
(2) boost::less_than_comparable 这个类要求实现 <, 可以自动实现 >, <=, >= (自动推导出来的,模板元的思想)
3、 学习流程
(1) 剥离代码 (在 ~/muduo_practice 下), 编译出来一个只有TimeStamp的base库(2) 小的测试程序在 ~/muduo_practice/tests 下 a. Bsa.cc 测试boost编译时断言的 -> BOOST_STATIC_ASSERT1 #include2 3 class Timestamp 4 { 5 private: 6 int64_t microseconds; 7 }; 8 9 BOOST_STATIC_ASSERT(sizeof(Timestamp) == sizeof(int64_t));10 //BOOST_STATIC_ASSERT(sizeof(short) == sizeof(int64_t));11 int main() {12 return 0;13 }
b. 测试PRId64
1 #include2 #include 3 #define _STDC_FORMAT_MACROS 4 #include 5 #undef _STDC_FORMAT_MACROS 6 7 int main(void) { 8 int64_t value = time(NULL); 9 printf("%"PRId64"\n", value);10 return 0;11 }
c. 设计一个合理的对TimeStamp类的benchmark
用一个vector数组存储Timestamp, 用Timestamp的微秒表示计算相邻两个时间戳的时间差。Vector需要提前reserve空间,避免内存开销影响benchmark。 代码见Timestamp_sara.cc1 //2017-10-29 2 //Add by wyzhang 3 //Learn Muduo -- test Timestamp 4 5 #include6 #include 7 #include 8 #define _STDC_FROMAT_MACROS 9 #include 10 #undef _STDC_FORMAT_MACROS11 12 using namespace muduo;13 14 // design a benchmark function to test class Timestamp15 // we can use a vector to record Timestamp, and calculate difference of neighbors16 void benchmark() {17 const int kNumbers = 1000 * 1000;18 std::vector vecTimestamp;19 vecTimestamp.reserve(kNumbers); //must preReserve. in case calculate the time of allocate mem20 for (int i = 0; i < kNumbers ; ++i ) {21 vecTimestamp.push_back(Timestamp::now());22 }23 24 int gap[100] = { 0};25 Timestamp start = vecTimestamp.front();26 for (int i = 1; i < kNumbers; ++i ) {27 Timestamp next = vecTimestamp[i];28 int64_t calGap = next.microSecondsSinceEpoch() - start.microSecondsSinceEpoch(); // use microSeconds here29 start = next;30 if(calGap < 0) {31 printf("calGap < 0\n");32 } else if (calGap < 100){33 gap[calGap]++;34 } else {35 printf("bigGap. [%"PRId64"]\n", calGap);36 }37 }38 for (int i = 0; i < 100; ++i) {39 printf("%d: %d\n", i, gap[i]);40 }41 }42 43 44 int main() {45 //[1] test print timestamp46 Timestamp ts(Timestamp::now());47 printf("print now = %s\n", ts.toString().c_str());48 sleep(1);49 Timestamp ts2 = Timestamp::now();50 printf("ts2 = %s\n", ts2.toString().c_str());51 double difftime = timeDifference(ts2, ts);52 printf("difftime: %f\n", difftime);53 //[2] run benchmark54 benchmark();55 return 0;56 }
执行结果截图如下:没有截全
二、Exception类
1、类图如下:
2、 知识点
(1) 系统调用:backtrace, 栈回溯,保存各个栈帧的地址
(2) 系统调用:backtrace_symbols, 根据地址,转成相应的函数符号
(3) abi::_cxa_demangle
(4) 抛出了异常,如果不catch,会core
3、 学习流程
(1) 测试程序如下
1 #include2 #include 3 4 class Bar 5 { 6 public: 7 void test() { 8 throw muduo::Exception("omg oops"); 9 }10 };11 12 void foo() {13 Bar b;14 b.test();15 }16 17 int main() {18 /* 只抛出异常,不捕获,会core */19 //foo();20 try {21 foo();22 }23 catch (muduo::Exception& ex) {24 printf("%s\n", ex.what());25 printf("\n");26 printf("%s\n", ex.stackTrace());27 }28 return 0;29 }
运行结果如下