C++编写一个打印对象生命期的类:
定义:
/* Execution timer class. */ class ExecuteTimer { public: ExecuteTimer(); ~ExecuteTimer(); /*\brief: Get char* type time. *\return: char* type time, unit:second. */ char* GetCTime(); /*\brief: Get double type time. *\return: double type time, unit:second. */ double GetDTime(); /*\brief: Reset the begin time. */ void Reset(); /*\brief: ostream << operator friend function. *\param: os, The left operation. *\param: obj, The right operation. *\return: std::ostream object ref.. */ friend std::ostream& operator << (std::ostream& os, ExecuteTimer& obj); /*\brief: ofstream << operator friend function. *\param: os, The left operation. *\param: obj, The right operation. *\return: std::ofstream object ref.. */ friend std::ofstream& operator << (std::ofstream& ofs, ExecuteTimer& obj); private: struct timespec m_begin; char m_ctime[32]; };
实现:
ExecuteTimer::ExecuteTimer() { memset(m_ctime, 0, sizeof(char)*32); //Reset the begin time. Reset(); } ExecuteTimer::~ExecuteTimer() { } char* ExecuteTimer::GetCTime() { double lt = GetDTime(); sprintf(m_ctime, "%.3fs", lt); return m_ctime; } double ExecuteTimer::GetDTime() { struct timespec end; clock_gettime(CLOCK_REALTIME, &end); //trans. to second unit. double lt = (end.tv_sec - m_begin.tv_sec) + (end.tv_nsec - m_begin.tv_nsec) * 1.0e-9; return lt; } void ExecuteTimer::Reset() { clock_gettime(CLOCK_REALTIME, &m_begin); } std::ostream& operator << (std::ostream& os, ExecuteTimer& obj) { double lt = obj.GetDTime(); //output formated string. char fmt[32] = {0}; sprintf(fmt, "%.3fs", lt); os << fmt; return os; } std::ofstream& operator << (std::ofstream& ofs, ExecuteTimer& obj) { double lt = obj.GetDTime(); //output formated string. char fmt[32] = {0}; sprintf(fmt, "%.3fs", lt); ofs << fmt; return ofs; }