Tracking Elapsed Time

Tracking Elapsed Time

This C++ class tracks elapsed time. The mark() method is called at the point of interest, after which there are methods to retrieve the elapsed time between points, total time, or average time. Implemented using the C++ template, it accepts different tick classes for getting the time at the marked point. Provided here are two tick classes?one with a C run time and the other with Win32 API:

#pragma once#include #include #include class Tick_CRT{public:	static clock_t get() 	{		return clock();	}	static double convert(clock_t end, clock_t start)	{		// in senconds		return (static_cast(end - start)) / CLOCKS_PER_SEC;	}};class Tick_WIN{public:	static unsigned long get() 	{		return GetTickCount();	}	static double convert(unsigned long end, unsigned long start)	{		// in senconds		unsigned long diff = 0;		if (end >= start)		{			diff = end - start;		}		else		{			diff = end + 0xFFFF - start;		}		return (static_cast(diff)) / 1000;	}};//templatetemplateclass Elapsed_Time  {public:	typedef std::vector Double_Vector;private:	typedef std::vector Tick_Vector;	Tick_Vector ticks_;	Double_Vector diff_;public:	Elapsed_Time() {}	virtual ~Elapsed_Time() {}	void reset()	{		ticks_.clear();		diff_.clear();	}	void mark()	{		ticks_.push_back(Ticker::get());	}	size_t mark_count()	{		return ticks_.size();	}	size_t diff_count()	{		return diff_.size();	}	size_t cal_diff()	{		diff_.clear();		if (mark_count() > 1)		{			Tick_Vector::iterator it0 = ticks_.begin();			std::transform(++it0, ticks_.end(), ticks_.begin(), std::back_inserter(diff_), std::ptr_fun(&Ticker::convert));		}		return diff_.size();	}	double diff(unsigned long i)	{		if (i >= 0 && i < diff_count())			return diff_[i];		else			return 0;	}	double sum()	{		double s = 0.0;		for(Double_Vector::iterator it = diff_.begin(); it != diff_.end(); it++)			s += *it;		return s;	}	double average()	{		if (diff_count() > 0)			return sum() / diff_count();		else			return 0.0;	}	Double_Vector & get_diff()	{		return diff_;	}};

Note: This source code has been tested using MS VC++ 6/7/8.

See also  Essential Measures for Safeguarding Your Digital Data

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist