Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating time by the C++ code

Tags:

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
like image 537
itsaboutcode Avatar asked Jan 31 '10 21:01

itsaboutcode


People also ask

How do you find the time taken to execute a program in C?

We can use the clock() function provided by the <time. h> header file to calculate the CPU time consumed by a task within a C application. It returns the clock_t type, which stores the total number of clock ticks.

What does time () do in C?

The time() function is defined in time. h (ctime in C++) header file. This function returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds. If second is not a null pointer, the returned value is also stored in the object pointed to by second.

How is execution time of a code calculated?

Firstly we can call StartNew() method in Stopwatch to start the elapsed time and at the end, we can call this method to end the current measuring time interval. Eventually, the total execution time is calculated with the help of elapsed property.

How do you track time in C++?

Since C++11, the best way to measure elapsed time in C++ is by using the Chrono library, which deals with time. Following C++ program calculates the time elapsed for a simple code in seconds, milliseconds, microseconds, and nanoseconds. It includes the <chrono.


2 Answers

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 ));
like image 134
Mark Wilkins Avatar answered Sep 19 '22 03:09

Mark Wilkins


You need a high precision timer. In case of Visual Studio use QueryPerformanceCounter.

If the precision is still not enough, use compiler intristics:

#include <intrin.h>
#pragma intrinsic(__rdtsc)

unsigned __int64 ticks = __rdtsc();

See info on that intristic here.

Both solutions are Windows only, the latter is probably MSVC only. I can post a similar solution for GCC/Linux if needed.

like image 30
Kornel Kisielewicz Avatar answered Sep 20 '22 03:09

Kornel Kisielewicz