0

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

Siva
  • 141
  • 1
  • 2
  • 12
  • 1
    If you want to profile your code, use [gprof](http://www.cs.utah.edu/dept/old/texinfo/as/gprof_toc.html). Alternatively, if you're familiar with MATLAB, you might like my [tictoc.h](https://github.com/rmartinjak/snippets/blob/master/tictoc/tictoc.h). – Brave Sir Robin Feb 03 '14 at 08:36
  • @rmartinjak : I'm not familiar with MATLAB bro.. That is the problem :( – Siva Feb 18 '14 at 05:33

1 Answers1

5

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:

Community
  • 1
  • 1