It's a very simple class, but I wrote what I'm calling a Timer, it has similar functionality to a stop watch. The Basic timer class relies on the Windows QueryPerformanceFrequency, so here's the function necessary for my Timer class:
Time.h
#ifndef w_Time
#define w_Time
#include "../Definitions.h"
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>
namespace _Warp
{
class Time
{
public:
static Real64 HiResTime()
{
u64 ticks;
u64 ticksPerSecond;
Bool result = QueryPerformanceFrequency((LARGE_INTEGER*) &ticksPerSecond);
if(result == 0)
{
return -1;
}
result = QueryPerformanceCounter((LARGE_INTEGER*) &ticks);
if(result == 0)
{
return -1;
}
return (Real64) ticks / ticksPerSecond;
}
};
};
#endif
Timer.h
#ifndef w_Timer
#define w_Timer
#include "../Definitions.h"
namespace _Warp
{
class Timer
{
protected:
Real64 _start;
Bool _running;
public:
Timer();
void Start();
void Stop();
void Reset();
Real64 Get_Microseconds() const;
Real64 Get_Milliseconds() const;
Real64 Get_Seconds() const;
Bool IsRunning() const;
};
};
#endif
Timer.cpp
#include "Timer.h"
#include "Time.h"
namespace _Warp
{
Timer::Timer()
: _start( 0 )
, _running( FALSE )
{
}
void Timer::Start()
{
// this allows the timer to continue from where it left off
_start = Time::HiResTime() - _start;
_running = TRUE;
}
void Timer::Stop()
{
if(_running == TRUE)
{
_start = Time::HiResTime() - _start;
_running = FALSE;
}
}
void Timer::Reset()
{
if(_running == TRUE)
{
_start = Time::HiResTime();
}
else
{
_start = 0;
}
}
Real64 Timer::Get_Microseconds() const
{
if(_running == TRUE)
{
return (Time::HiResTime() - _start) * 1000000.0;
}
return _start * 1000000.0;
}
Real64 Timer::Get_Milliseconds() const
{
if(_running == TRUE)
{
return (Time::HiResTime() - _start) * 1000.0;
}
return _start * 1000.0;
}
Real64 Timer::Get_Seconds() const
{
if(_running == TRUE)
{
return Time::HiResTime() - _start;
}
return _start;
}
Bool Timer::IsRunning() const
{
return _running;
}
};
Here is a sample of how to use my timer class:
Timer timer = Timer();
timer.Start();
/* do stuff here */
timer.Stop();
Real64 seconds = timer.Get_Seconds();
timer.Reset();//reset the timer so it's total count is back to zero seconds.
timer.Start();
/* time something else */
timer.Stop();
/* do something */
timer.Start();//continue the count from where the timer left off
/* time something again*/
timer.Stop();
seconds = timer.Get_Seconds();// this is the total count of seconds from the last two timing sessions since Reset wasn't called
You can find the blog on the Definition.h file here.
Or download all of the above files and Definition.h here: Timer project files.
Comments