Saturday 22 August 2009

Measuring elapsed time in C++ using timeGetTime()

Continuing our theme of Performance Measurement by getting the elapsed time between different instances, today we look at another approach using timeGetTime() method. The code and approach is the same as GetTickCount() case except that the call is replaced.

So whats the difference and which one is better. timeGetTime() has a default resolution of around 5ms but by using the timeBeginPeriod(1) the accuracy can be made upto 1ms. GetTickCount accuracy and jitter cannot be guaranteed. timeGetTime() has more overhead than GetTickCount() so it should not be used in the case where the calls will be frequently made.

Another thing which may be obvious is that GetTickCount() actually calculates the time based on the number of clock interrupts and multiplies it by clock frequency. timeGetTime() reads a field called interrupt time which is updated by Kernel periodically.

Finally, if possible always use QueryPerformanceCounter() as thats better and receommended.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows example of Getting Elapsed Time
#include <iostream>
#include <Windows.h>

using namespace
std;

unsigned long
startTime_;

void
startTime()
{

startTime_ = timeGetTime();
}


unsigned int
calculateElapsedTime()
{

unsigned int
diffInMilliSeconds = timeGetTime() - startTime_;
return
diffInMilliSeconds;
}


int
main()
{

//Increasing the accuracy of Sleep to 1ms using timeBeginPeriod
timeBeginPeriod(1); //Add Winmm.lib in Project
unsigned int diffTime = 0, lastTime = 0, newTime = 0;
startTime();
cout<<"Start Time = "<<calculateElapsedTime()<<endl;

Sleep(100);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 100ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;

Sleep(100);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 100ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;

Sleep(5);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 5ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
lastTime = newTime;

Sleep(50);
newTime = calculateElapsedTime();
diffTime = newTime - lastTime;
cout<<"Time after 50ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;

timeEndPeriod(1); //Must be called if timeBeginPeriod() was called
return 0;
}


The output is as follows. Notice more reliable and jitter free output:

No comments:

Post a Comment