在浅尝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_;
};
由于boost的date_time提供了静态库,不用再扯上一个DLL,让人的感觉会好一些;而且boost也更适用于这个层面的代码,ACE毕竟是框架级别的库。