/*

Copyright (c) 2002-2005, Yauheni Akhotnikau
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

- The name of the author may not be used to endorse or promote products derived
from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.

*/

#if !defined( _TIME_METER_HPP_ )
#define _TIME_METER_HPP_

#include <string>
#include <ctime>

namespace oess_1
{

namespace debug
{

class	time_accumulator_t
	{
	private :
		std::string	m_name;
		double	m_value;
		double	m_max_delta;
		unsigned int	m_count;

	public :
		inline time_accumulator_t(
			const std::string & name )
			:	m_name( name )
			,	m_value( 0 )
			,	m_max_delta( 0 )
			,	m_count( 0 )
			{}

		inline ~time_accumulator_t()
			{
				std::cout << m_name << ": " << m_value
					<< " (max: " << std::fixed << m_max_delta
					<< ", avg: " << std::fixed << ( m_count ? m_value / m_count : 0.0 )
					<< ", cnt: " << m_count << ")" << std::endl;
			}

		inline void
		operator+=( double delta )
			{
				if( delta < 0.00000001 )
					delta = 0.00000001;

				m_value += delta;
				++m_count;
				if( m_max_delta < delta )
					m_max_delta = delta;
			}
	};

class	time_meter_t
	{
	private :
		time_accumulator_t &	m_accumulator;
		std::clock_t	m_start;

	public :
		inline time_meter_t(
			time_accumulator_t & accumulator )
			:	m_accumulator( accumulator )
			,	m_start( std::clock() )
			{}

		inline ~time_meter_t()
			{
				std::clock_t finish = std::clock();
				m_accumulator += double( finish - m_start ) / CLOCKS_PER_SEC;
			}
	};

} /* namespace debug */

} /* namespace oess_1 */

#endif
