AutoTimer “Making Pimpl Easy”版

AutoTimer.h

#include <boost/enable_shared_from_this.hpp>

#include <string>

using namespace std;



class AutoTimer : public pimpl<AutoTimer>::pointer_semantics,

	  public boost::enable_shared_from_this<AutoTimer>

{

public:

	AutoTimer(const std::string &name);

	~AutoTimer(void);

};

AutoTimer.cpp

#include "AutoTimer.h"

#include <iostream>

#include <windows.h>

#include <string>



template<> struct pimpl<AutoTimer>::implementation

{

	implementation (string k) : mName(k)   

	{ 

		mStartTime = GetTickCount();

	}



	double GetElapsed() const;



	string mName;

	DWORD mStartTime;



};



template<> double pimpl<AutoTimer>::implementation::GetElapsed() const

{

	return (GetTickCount()-mStartTime) / 1e3;

}



AutoTimer::AutoTimer (const std::string &name) : base(name) 

{



}



AutoTimer::~AutoTimer(void)

{

	 implementation const& self = **this;

	 std::cout<<self.mName<< ": took " << self.GetElapsed()

	 	<< " secs" << std::endl;

}



main.cpp

int _tmain(int argc, _TCHAR* argv[])

{

	AutoTimer timer("MyTimer");



	for (int i = 0; i < 1000; ++i)

	{

		cout << ".";

	}

	cout << endl;



	return 0;

}

你可能感兴趣的:(timer)