Mark
Mark

Reputation: 6494

C: measure time of operation in Linux

I need to measure a time inside the C program. I googled and found two options: gettimeofday() and time() syscalls. For example:

#include <time.h>

...

time_t start, end;
double seconds;

time(&start);

/* Run some complex algorithm  ... */

time(&end);
seconds = difftime(end, start);

Or

#include <sys/time.h>
...
struct timeval start, end;
double elapsed_time;

gettimeofday(&start, NULL);

/* Data processing */

gettimeofday(&end, NULL);

/* calculate time in ms. */
elapsed_time = (end.tv_sec - start.tv_sec) * 1000.0;
elapsed_time += (end.tv_usec - start.tv_usec) / 1000.0;

So as I understand, the 2nd method is giving higher accuracy (milli/microseconds), while the first one returns elapsed time only in seconds. Am I right?

Upvotes: 0

Views: 209

Answers (1)

Nate Eldredge
Nate Eldredge

Reputation: 58715

Yes, your understanding is correct.

There is also clock_gettime which provides nanosecond resolution. (Whether it actually has nanosecond accuracy depends on your hardware.)

Upvotes: 1

Related Questions