Timeval struct usage

2019-08-26 02:20发布

问题:

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.. !!

回答1:

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:

  • http://linux.die.net/man/3/clock_gettime
  • Use of clock_getres - newbie Linux C