Timeval struct usage

Siva picture Siva · Feb 3, 2014 · Viewed 8.9k times · Source

I needed to calculate the time it takes to run a certain function and ran into the following code,record & output the execution time of a piece of code in nanoseconds

And also is there any difference between

struct timeval timer_spent & timeval timer_spent

/* Put this line at the top of the file: */
#include <sys/time.h>

/* Put this right before the code you want to time: */
struct timeval timer_start, timer_end;
gettimeofday(&timer_start, NULL);

/* Put this right after the code you want to time: */
gettimeofday(&timer_end, NULL);
double timer_spent = timer_end.tv_sec - timer_start.tv_sec + (timer_end.tv_usec - timer_start.tv_usec);
printf("Time spent: %.6f\n", timer_spent)/1000000.0;

But I need the precise timing in nanoseconds. I've no complete idea about the timeval struct.

So kindly help me guys.. !!

Answer

user184968 picture user184968 · Feb 3, 2014

But I need the precise timing in nanoseconds.

Then use

int clock_gettime(clockid_t clk_id, struct timespec *tp);

It returns time in seconds and nanoseconds

struct timespec {
  time_t   tv_sec;        /* seconds */
  long     tv_nsec;       /* nanoseconds */
};

Useful links: