Reputation: 429
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
Reputation: 1630
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
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
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