Laurens Vandenbroucke

Article information: Language: C++
Platform: Windows, Linux, apple





Introduction


When developing a game or application it is most likely that you will come in contact with time.
Example: frame independent rendering

In this article I'll show you how to create and use a 'High-Performance Timer' and a 'General Tick Timer'

Getting Time data


We could use the clock() function from <time.h> which returns the approximation of processor time.
But clock() can't register very short processor times.
So we must use a system dependent timer.

High-'performance' timer
This is a microsecond precision timer,
On the windows platform we could use
BOOL WINAPI QueryPerformanceCounter(LARGE_INTEGER *lpPerformanceCount);
Expand/hide Windows High-performance timer



on Linux we should use
int clock_gettime(clockid_t clock_id, struct timespec *tp);
Expand/hide Linux High-performance timer



and on a Mac (apple) platform
uint64_t mach_absolute_time();
Expand/hide Apple High-performance timer

When combined, the cross-platform timer class souled look like this: Show complete Timer class Source


General 'Tick' Timer
A Tick Timer is a fast timer with millisecond precision.

Expand/hide Windows Tick timer



Remarks


a high performance timer is preciser but also slower, it should only be used on profiling tasks.
For all the other time measurement you should use a "General use timer", its less precise but it will do the task.
Notice: Timers could return incorrect results due system error, overload, hibernation,...
So check always if your results is within a acceptable range.

void Tick()
{
	const float fMaxTimeDiff = 2.5f;
	
	//get the time in sec between the last Reset/start call and now
	float fTimeDiff = m_TimerPtr->GetElapsedTime();
	//making sure that the elapsed time is not exceeding the Maximum Time Difference
	if(fTimeDiff > fMaxTimeDiff)fTimeDiff = fMaxTimeDiff;
	
	//calling a function with the elapsed time as param
	Update(fTimeDiff);
	
	m_TimerPtr->Reset();
}


Light Dark
Blue Red Grey Purple Green