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
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.
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.
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.
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.
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 ));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With