/*******************************************************************************
 *	BTimer.cpp	Quantel Quentin BTimer
 *			T.Barnaby,	BEAM Ltd,	3/2/04
 *******************************************************************************
 */
#include <BTimer.h>
#include <sys/time.h>

BTimer::BTimer(){
	clear();
}

BTimer::~BTimer(){
}

double BTimer::getTime()
{
	struct timeval	tp;
	
	gettimeofday(&tp, NULL);
	return ((double) tp.tv_sec + (double) tp.tv_usec * 1e-6);
}

void BTimer::add(BTimer& timer){
	timer.olock.lock();
	olock.lock();
	
	onum += timer.onum;
	oaverage += timer.oaverage;
	if(timer.opeak > opeak)
		opeak = timer.opeak;
		
	olock.unlock();
	timer.olock.unlock();
}

void BTimer::clear(){
	olock.lock();
	onum = 0;
	ostartTime = 0.0;
	oendTime = 0.0;
	oaverage = 0.0;
	opeak = 0.0;
	olock.unlock();
}

void BTimer::start(){
	olock.lock();
	ostartTime = getTime();
	oendTime = 0.0;
	olock.unlock();
}

void BTimer::stop(){
	olock.lock();
	oendTime = getTime();

	onum++;
	oaverage += (oendTime - ostartTime);
	if((oendTime - ostartTime) > opeak){
		opeak = (oendTime - ostartTime);
	}
	olock.unlock();
}

double BTimer::getElapsedTime(){
	double	t;

	olock.lock();
	t = getTime() - ostartTime;
	olock.unlock();

	return t;
}

double BTimer::average(){
	double ret;
	
	olock.lock();
	ret = oaverage / onum;
	olock.unlock();
	return ret;
}

double BTimer::peak(){
	double ret;
	
	olock.lock();
	ret = opeak;
	olock.unlock();
	return ret;
}
