Tim
A timer implemented as a function object
I view function objects in their purest
form as functions with data members which is exactly how
this function object is implemented.
Each Tim object contains a start, stop and elapsed time.
Using this approach, a sequence of timed events can be
calculated and stored in an array of Tims.
There is also the option of pausing for a specified
number of seconds.
| class Tim |
#include <iostream>
#include <time.h>
#include <stdio.h>
|
|
class Tim{
public:
void operator () (bool); // start and stop
void operator () (int); // pause
time_t Elapsed();// {return elapsed;};
void Reset();// {start=0; stop=0; elapsed=0;};
private:
time_t start,
stop,
elapsed;
};
void
Tim::operator () (bool com)
{
if(com)
start=time(0);
if(!com) {
stop=time(0);
elapsed= stop -start;
}
};
void
Tim::operator () (int pause)
{
start =time(0);
while(time(0)<start+pause)
;
};
inline time_t
Tim::Elapsed()
{
return elapsed;
};
inline void
Tim::Reset()
{
start=0; stop=0; elapsed=0;
};
|
|
|
| Driver |
|
void main()
{
Tim tim;
cout<<"Press a key to start timer"<<endl;
getchar();
tim(true);
cout<<"Press a key to stop timer"<<endl;
getchar();
tim(false);
cout<<"The time elapsed was: "<<tim.Elapsed()<<"
seconds"<<endl;
tim.Reset();
int secs;
cout<<"Enter the no of seconds you wish to pause for:
"; cin>>secs;
cout<<"\nPausing..."<<endl;
tim(secs);
cout<<"Press a key to exit"<<endl;
getchar();
}; // main
|
|
|
|
|