How can I calculate the execution time in the following code:
#include /* Core input/output operations */
#include
I'd try the following :
int timeval_subtract ( struct timeval *result, struct timeval *x, struct timeval *y ) {
if ( x->tv_usec < y->tv_usec ) {
int nsec = ( y->tv_usec - x->tv_usec ) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = ( x->tv_usec - y->tv_usec ) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
return x->tv_sec < y->tv_sec;
}
void Start ( struct timeval *timer_profiling ) {
if ( timer_profiling == NULL ) return;
gettimeofday ( timer_profiling , NULL );
return;
}
void End ( struct timeval *timer_profiling , char *msg ) {
struct timeval res;
struct timeval now;
gettimeofday ( &now , NULL );
if ( msg == NULL ) return;
timeval_subtract ( &res , &now , timer_profiling );
sprintf ( msg , "[ %ld,%.3ld ms]" , res.tv_sec*1000 + (long)round(res.tv_usec/1000) , res.tv_usec - (long)round(res.tv_usec/1000)*1000);
return;
}
Start(&s) one with an allocated timer_profiling , then retrieve the result in a string by calling End(&s,buff);