Thursday 20 August 2009

Measuring elapsed time in C++ using GetTickCount()

There are variety of ways to obtain the elapsed time in a program. We will look at some of the ways in the next few posts. The first approach is using the GetTickCount() method. It should be mentioned that this method is not very accurate and some people have gone to the extent of saying that this should be deleted from the standards. Nevertheless it is quite widely used for cases where high resolution is not required.




//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_ = GetTickCount();
}


unsigned int
calculateElapsedTime()
{

unsigned int
diffInMilliSeconds = GetTickCount() - 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:

No comments:

Post a Comment