作者:吴尔平
转自:http://www.cnblogs.com/WuErPIng/archive/2005/09/21/241407.html
在浅尝boost之timer的post里,我提到boost::timer在linux和windows下的不同表现,并用ACE_OS::gettimeofday做了一个替代方案。不过,为了这个功能把ACE的DLL绑到一起,感觉不是那么愉快。
下面是另一个方案,利用boost::date_time库来解决
#include <boost/date_time/posix_time/posix_time.hpp>
class ElapsedTime
{
public:
ElapsedTime(): start_time_(boost::posix_time::microsec_clock::local_time())
{
}
~ElapsedTime()
{
}
void restart()
{
start_time_ = boost::posix_time::microsec_clock::local_time();
}
double Elapsed()
{
boost::posix_time::time_duration d = boost::posix_time::microsec_clock::local_time() - start_time_;
double result = d.ticks();
return result /= d.ticks_per_second();
}
private:
boost::posix_time::ptime start_time_;
};
class ElapsedTime
{
public:
ElapsedTime(): start_time_(boost::posix_time::microsec_clock::local_time())
{
}
~ElapsedTime()
{
}
void restart()
{
start_time_ = boost::posix_time::microsec_clock::local_time();
}
double Elapsed()
{
boost::posix_time::time_duration d = boost::posix_time::microsec_clock::local_time() - start_time_;
double result = d.ticks();
return result /= d.ticks_per_second();
}
private:
boost::posix_time::ptime start_time_;
};