user3126802
user3126802

Reputation: 429

Timing a function in C

I'm trying to find out the time it takes for a function to execute in C. What i'm trying is the following:

#include <time.h>

time_t start;
time_t finish;
double seconds;

time(&start);
FUNCTION
time(&finish);

seconds = difftime(finish,start);

printf("Time taken is %.f", seconds);

However, the returned value is always the same for different functions: 1389133144 seconds.

Any help? Thanks!

Upvotes: 0

Views: 249

Answers (3)

The time function returns the number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). If the argument is non-NULL, it also stores the time in it.

1389133144 is actually a pretty reasonable timestamp, it is 2014-01-07 22:19:04.

However, the time function is not a very good tool to measure the run time of a function, since the precision is very low. Consider using gettimeofday, clock_gettime or simply clock, all of which should be more precise.

Upvotes: 1

dacuna
dacuna

Reputation: 1096

Other approach I commonly use is something like this:

#include <sys/time.h>

//this is from http://www.cs.usfca.edu/~peter/ipp/
#define GET_TIME(now) { \
   struct timeval t; \
   gettimeofday(&t, NULL); \
   now = t.tv_sec + t.tv_usec/1000000.0; \
}

//in your code
double start, end;
GET_TIME(start);
//... do some stuff...
GET_TIME(end);

printf("TOTAL TIME = %f secs\n", end-start);

Upvotes: 1

BradHards
BradHards

Reputation: 702

The problem isn't in the time calculations, its in the format specifier for the printf() statement. You are using "%.f", where you probably want "%f". The . means precision in this context.

Upvotes: 0

Related Questions