view modules/elapsed-timer/elapsed-timer.hpp @ 532:33f98fda1884

ElapsedTimer: import
author David Demelier <markand@malikania.fr>
date Thu, 02 Jun 2016 16:56:44 +0200
parents
children f48bb09bccc7
line wrap: on
line source

/*
 * elapsed-timer.hpp -- measure elapsed time
 *
 * Copyright (c) 2013-2016 David Demelier <markand@malikania.fr>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#ifndef ELAPSED_TIMER_HPP
#define ELAPSED_TIMER_HPP

/**
 * \file elapsed-timer.hpp
 * \brief Measure elapsed time
 */

#include <chrono>

/**
 * \brief Measure elapsed time
 *
 * This class provides an abstraction to measure elapsed time since the construction of the object. It uses
 * std::chrono::high_resolution_clock for more precision and uses milliseconds only.
 */
class ElapsedTimer {
private:
	using TimePoint = std::chrono::time_point<std::chrono::high_resolution_clock>;

	TimePoint m_last;
	bool m_paused{false};
	unsigned m_elapsed{0};

public:
	/**
	 * Construct the elapsed timer, start counting.
	 */
	inline ElapsedTimer() noexcept
		: m_last(std::chrono::high_resolution_clock::now())
	{
	}

	/**
	 * Put the timer on pause, the already elapsed time is stored.
	 */
	inline void pause() noexcept
	{
		/*
		 * When we put the timer on pause, do not forget to set the already
		 * elapsed time.
		 */
		elapsed();
		m_paused = true;
	}

	/**
	 * Restart the timer, does not reset it.
	 */
	inline void restart() noexcept
	{
		m_paused = false;
		m_last = std::chrono::high_resolution_clock::now();
	}

	/**
	 * Reset the timer to 0.
	 */
	inline void reset() noexcept
	{
		m_elapsed = 0;
		m_last = std::chrono::high_resolution_clock::now();
	}

	/**
	 * Get the number of elapsed milliseconds.
	 *
	 * \return the milliseconds
	 */
	inline unsigned elapsed() noexcept
	{
		using std::chrono::duration_cast;
		using std::chrono::high_resolution_clock;
		using std::chrono::milliseconds;

		if (!m_paused) {
			m_elapsed += duration_cast<milliseconds>(high_resolution_clock::now() - m_last).count();
			m_last = high_resolution_clock::now();
		}

		return m_elapsed;
	}
};

#endif // !ELAPSED_TIMER_HPP