Tuesday, April 19, 2011

time measure in C - Windows GetTickCount() example

This time measure routine uses GetTickCount() function of Windows. Thought it does not give exact CPU cycles of the code fragment, you can get a rough real-life measurement from this. Time measure routine using GetTickCount() is shown below.
 


 
//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;
}