"Vasileios" <va*******@zografos.org> wrote in message
news:40**************************@posting.google.c om...
Hi everyone.
I am trying to time how long a function takes to execute in c++.
Lets say I have a loop for example:
for (int i=0;i<1000; i++)
{
...do something useful here
}
I would like to measure how long this loop takes to execute in
miliseconds or seconds.
How can I do that?
I thought of using time() to get the current time before the loop, and
once again after the loop has finished.
However this doesnt seem very robust. Can you perhaps recommend
another way?
For (more or less) exact measurements I'd personally recommend the use of
profilers. However, you can certainly resort to the use of the time()
function but in order to obtain representative measurements the timing must
be repeated a couple of times. To do this you could use the following macro:
////////////////////////////////////////////////////////////////////////////
//
// BENCH
// benchmark for function timing.
// e.g.:
//
// double t;
// BENCH( sort( Vec.begin(), Vec.end() ), "sort of Vec", 2.0, t );
////////////////////////////////////////////////////////////////////////////
//
#define BENCH( Block, Name, TimeOut, t) \
{ \
time_t ts, te; \
double total_t; \
int ni = 1; \
do { \
ts = time((time_t *)NULL); \
for( int i = 0; i < ni; i++) { \
Block; \
} \
te = time((time_t *)NULL); \
t = (total_t=(te - ts)) / ni; \
ni <<= 1; \
} while( total_t < TimeOut); \
std::cout << "time for one " << Name << " = " << t << " secs" <<
std::endl; \
} \
HTH
Chris