C++ Time Calculation – Efficient Methods and Examples

c++

I know this question has been asked few times over SO but none of them is really helping me out, so asking again.

I am using windows xp and running visual studio c++ 2008.

All the code which i am looking is using time.h but i think may be its not working correctly here, because results are making me suspicious.

So this is what i want.

star time = get time some how (this is my question)

my code

end time = get time some how (this is my question)

time passed = start time - end time

Best Answer

Here is what I use to print time in milliseconds.

void StartTimer( _int64 *pt1 )
{
   QueryPerformanceCounter( (LARGE_INTEGER*)pt1 );
}

double StopTimer( _int64 t1 )
{
   _int64 t2, ldFreq;

   QueryPerformanceCounter( (LARGE_INTEGER*)&t2 );
   QueryPerformanceFrequency( (LARGE_INTEGER*)&ldFreq );
   return ((double)( t2 - t1 ) / (double)ldFreq) * 1000.0;
}

Use it like this:

    _int64 t1;

    StartTimer( &t1 );

    // do some stuff

    printf( "Time = %.3f\n", StopTimer( t1 ));