c++ 记录耗时类

// .h
/**
 * @brief 耗时记录类
*/
class Timer
{
public:
	Timer();
	~Timer();

public:
	static Timer* getInstance();

public:
	enum TimeFormat
	{
		TF_S,
		TF_MS,
		TF_US,
		TF_NS
	};

	/**
	 * @brief 开始记录时间
	*/
	void start();

	/**
	 * @brief 统计耗时
	 * @param [in] TimeFormat 时间格式
	 * @return -1=未设置开始时间,否则返回耗时
	*/
	double finish(TimeFormat timeFor = TF_MS) const;

private:
	class Impl;
	std::unique_ptr<Impl> impl_;
};
// .cpp
/**
 * @brief 耗时记录类
*/
class Timer::Impl
{
public:
	Impl();
	~Impl();

public:
	std::stack<std::chrono::steady_clock::time_point> Timer;

public:
	int capacity_;
};

Timer::Impl::Impl()
{
	capacity_ = STK_SIZE;
}

Timer::Impl::~Impl()
{
	while (!Timer.empty())
	{
		Timer.pop();
	}
}

Timer::Timer()
{
	impl_ = std::make_unique<Impl>();
}

Timer::~Timer()
{
}

Timer *Timer::getInstance()
{
	static Timer ins;
	return &ins;
}

void Timer::start()
{
	if (impl_->Timer.size() == impl_->capacity_)
		impl_->capacity_ += STK_SIZE;

	impl_->Timer.push(std::chrono::steady_clock::now());
}

double Timer::finish(TimeFormat timeFor) const
{
	if (impl_->Timer.empty())
		return -1;

	auto t_end = std::chrono::steady_clock::now();
	decltype(t_end) t_begin = impl_->Timer.top();
	impl_->Timer.pop();

	auto tempElapsed = t_end - t_begin;
	double elapsed = 0.0;

	switch (timeFor)
	{
	case TimeFormat::TF_S:
		elapsed = std::chrono::duration_cast<std::chrono::seconds>(tempElapsed).count();
		break;
	case TimeFormat::TF_MS:
		elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(tempElapsed).count();
		break;
	case TimeFormat::TF_US:
		elapsed = std::chrono::duration_cast<std::chrono::microseconds>(tempElapsed).count();
		break;
	case TimeFormat::TF_NS:
		elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(tempElapsed).count();
		break;
	default:
		break;
	}

	return elapsed;
}

你可能感兴趣的:(C++/C,c++,笔记)