社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
#ifndef AUTOTIMER_H_
#define AUTOTIMER_H_
#include <string.h>
class AutoTimer
{
public:
explicit AutoTimer(const std::string name);
~AutoTimer();
private:
class Imple;
Imple * mimpl;
};
#endif /* AUTOTIMER_H_ */
#include "autotimer.h"
#include <iostream>
#if _WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif
class AutoTimer::Imple
{
public:
double GetElapsed() const
{
#ifdef _WIN32
return (GetTickCount() - mSmStartTime) / 1e3;
#else
struct timeval mEndTime;
gettimeofday(&mEndTime, NULL);
double t1 = mStartTime.tv_usec/1e6 + mStartTime.tv_sec ;
double t2 = mEndTime.tv_usec/1e6 + mEndTime.tv_sec ;
return t2 - t1;
#endif
}
std::string mName;
#ifdef _WIN32
DWORD mStartTime;
#else
struct timeval mStartTime;
#endif
};
AutoTimer::AutoTimer(const std::string name):mImpl(new AutoTimer::Imple)
{
mimpl->mName = name;
#ifdef _WIN32
mimpl->mStartTime = GetTickCount();
#else
gettimeofday(&mimpl->mStartTime, NULL);
#endif
}
AutoTimer::~AutoTimer()
{
std::cout << mimpl->mName << ": took" << mimpl->GetElapsed()
<< "secs" << std::endl;
delete mimpl;
mimpl = NULL;
}
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!