Episode usage of ‘gettimeofday()’ and ‘times()‘
On Unix/Linux machine to measure the time consumption for certain function call, ‘gettimeofday’/’times’ would be 2 major ways. Better than ‘gettimeofday’, ‘times’ could provide detailed time info for user, system, child…
1. gettimeofday()
#include <sys/time.h>
struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* microseconds */
};
struct timeval tpstart,tpend;
float timeuse = 0;
gettimeofday(&tpstart,NULL);
// function call
function_call();
gettimeofday(&tpend,NULL);
timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;
timeuse/=1000000;
printf(“Total time on function_call() is %fn”, timeuse);
2. times()
#include <sys/times.h>
#include <unistd.h> // used by sysconf()
struct tms {
clock_t tms_utime; /* user time */
clock_t tms_stime; /* system time */
clock_t tms_cutime; /* user time of children */
clock_t tms_cstime; /* system time of children */
};
struct tms time_buf_head, time_buf_end;
long tck = 0;
clock_t time_head, time_end;
tck = sysconf (_SC_CLK_TCK);
time_head = times( &time_buf_head );
// function call
function_call();
time_end = times( &time_buf_end );
printf(“function_call(), user time: %f, sys time: %f, child user time: %f, child sys time: %fn”,
((time_buf_end.tms_utime – time_buf_head.tms_utime) / (double)tck),
((time_buf_end.tms_stime – time_buf_head.tms_stime) / (double)tck),
((time_buf_end.tms_cutime – time_buf_head.tms_cutime) / (double)tck),
((time_buf_end.tms_cstime – time_buf_head.tms_cstime) / (double)tck) );