标签:res one include types.h ediff space closed 模板元 case
一、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_ASSERT
1 #include <boost/static_assert.hpp> 2 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 #include <cstdio> 2 #include <ctime> 3 #define _STDC_FORMAT_MACROS 4 #include <inttypes.h> 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.cc
1 //2017-10-29 2 //Add by wyzhang 3 //Learn Muduo -- test Timestamp 4 5 #include <muduo/base/Timestamp.h> 6 #include <cstdio> 7 #include <vector> 8 #define _STDC_FROMAT_MACROS 9 #include <inttypes.h> 10 #undef _STDC_FORMAT_MACROS 11 12 using namespace muduo; 13 14 // design a benchmark function to test class Timestamp 15 // we can use a vector to record Timestamp, and calculate difference of neighbors 16 void benchmark() { 17 const int kNumbers = 1000 * 1000; 18 std::vector<Timestamp> vecTimestamp; 19 vecTimestamp.reserve(kNumbers); //must preReserve. in case calculate the time of allocate mem 20 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 here 29 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 timestamp 46 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 benchmark 54 benchmark(); 55 return 0; 56 }
执行结果截图如下:没有截全
标签:res one include types.h ediff space closed 模板元 case
原文地址:http://www.cnblogs.com/zhangwanying/p/7750610.html