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 classesone with a C run time and the other with Win32 API:
#pragma once
#include <ctime>
#include <vector>
#include <algorithm>
class Tick_CRT
{
public:
static clock_t get()
{
return clock();
}
static double convert(clock_t end, clock_t start)
{
// in senconds
return (static_cast<double>(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<double>(diff)) / 1000;
}
};
//template<typename Ticker = Tick_WIN, typename Tick_Type = unsigned long>
template<typename Ticker = Tick_CRT, typename Tick_Type = clock_t>
class Elapsed_Time
{
public:
typedef std::vector<double> Double_Vector;
private:
typedef std::vector<Tick_Type> 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.