C++/Calculate function Running time
Expert: Zlatko - 9/20/2010
QuestionI have to make efiiciency check for diffrent traversal like
preorder,inorder and postorder.
I have make a switch case for user selection and difffrent
proceducers for the traversal and these procedurers are
recursive.
My Problem is that when i calculate time in the procedure
they calculate and print in vrious time i.e how many time it
does recurstion. And i calculate it in switch case it gives
start time and end time same can u help me out to solve this
??
AnswerHello Hetal
If you are using the Windows operating system, you can use the two calls to QueryPerformanceCounter to calculate the time a function call took. If you are using Linux, please let me know.
The sample code below shows how to time a function call. For this test, the Sleep function is being timed. The code below compiles with Visual Studio. If you are using Turbo C++, you may need to change
#include <iostream>
to
#include <iostream.h>
and you may need to remove the line:
using namespace std;
I do not have Turbo C++, so I don't know what else would need to be done.
The QueryPerformanceCounter returns the value of the CPU high-resolution counter. The functions below use that value, and the counter frequency to calculate elapsed time in milliseconds. If you don't care about milliseconds, but just want the elapsed time in counter ticks, then the code can be made even simpler.
I hope that helps you out. Let me know if you have any other questions.
Best regards
Zlatko
#include "Windows.h"
typedef unsigned __int64 PC_t;
PC_t PerfCounterFreq(void)
{
static PC_t result = 0;
if (result == 0)
{
LARGE_INTEGER li;
QueryPerformanceFrequency(&li);
result = (PC_t)li.QuadPart;
}
return result;
}
PC_t PerfCounter(void)
{
LARGE_INTEGER result;
QueryPerformanceCounter(&result);
return (PC_t)result.QuadPart;
}
double ElapsedMs(PC_t start)
{
return double(PerfCounter() - start)/PerfCounterFreq()*1000.0;
}
#include <iostream>
using namespace std;
int main(void)
{
PC_t start;
double ms;
start = PerfCounter();
Sleep(1000);
ms = ElapsedMs(start);
cout << "That took " << ms << " ms.\n";
return 0;
}