用于记录开始时间,结束时间,并且可以在任意地方打印记录的时间。 精确级别微秒。 #include <sys/time.h> #include <iostream> #include <vector> #include <map> class TIME{ private: std::map<std::string,std::vector<long> > m_TimeStampMap; public: bool record_time_begin( const std::string& name){ std::vector<long> timenum; struct timeval t; gettimeofday(&t , NULL); timenum.push_back(t.tv_sec); timenum.push_back(t.tv_usec); m_TimeStampMap.insert(std::make_pair(name,timenum)); return true; } bool record_time_end( const std::string& name){ std::map<std::string,std::vector<long> >::iterator i; i = m_TimeStampMap.find(name); if(i == m_TimeStampMap.end()){ return false; }else{ struct timeval t; gettimeofday(&t , NULL); (i->second).push_back(t.tv_sec); (i->second).push_back(t.tv_usec); } return true; } bool print_time( const std::string& name, std::ostream &ofp = std::cout ){ std::map<std::string,std::vector<long> >::iterator i; i = m_TimeStampMap.find(name); if(i != m_TimeStampMap.end()) { if( (i->second).size() == 2 ){ struct timeval t; gettimeofday(&t , NULL); ofp<<"TimeCost["<<name<<"] : "<<(t.tv_sec-(i->second)[0])*1000+(t.tv_usec-(i->second)[1])/1000<<" millisecond ("; ofp<<(t.tv_sec-(i->second)[0])*1000000+(t.tv_usec-(i->second)[1])<<" microsecond)"<<"/n"; m_TimeStampMap.erase(i); }else{ ofp<<"TimeCost["<<name<<"] : "<<((i->second)[2]-(i->second)[0])*1000+((i->second)[3]-(i->second)[1])/1000<<" millisecond ("; ofp<<((i->second)[2]-(i->second)[0])*1000000+((i->second)[3]-(i->second)[1])<<" microsecond)"<<"/n"; m_TimeStampMap.erase(i); } return true; } else return false; } };