Reputation: 269
The result that is printed is always zero (0.00) and I want to know what I am doing wrong. The first function returns the beginning time and the second the final time.
#include <sys/time.h>
#include <time.h>
void getTime(struct timeval begin){
gettimeofday(&(begin), (struct timezone*) 0);
}
float elapTime(struct timeval begin, struct timeval end){
return (1e+6*((end).tv_sec - (begin).tv_sec) + ((end).tv_usec - (begin).tv_usec));
}
int main(int argc, char **argv) {
struct timeval begin, end;
getTime(begin);
printf("Time: %.2f", elapTime(begin, end));
}
Upvotes: 2
Views: 116
Reputation: 169
You could do something like this instead:
#include <time.h>
#include <stdio.h>
int main() {
clock_t begin, end;
int i = 1e8;
begin = clock();
while(i--);
end = clock();
printf("Time: %.2f\n", (double) (end-begin)/CLOCKS_PER_SEC);
}
The clock()
function counts processor clock cycles. By dividing it by CLOCKS_PER_SEC
you get seconds. The code above counts the time it takes to iterate 1e8 down to 0.
Upvotes: 1
Reputation: 448
Try using more simple functions:
double floattime (void)
{
struct timeval t;
if (gettimeofday (&t, (struct timezone *)NULL) == 0)
return (double)t.tv_sec + t.tv_usec * 0.000001;
return (0);
}
int main(int argc, char **argv) {
double begin;
begin = floattime();
getchar ();
printf("Time: %.2f", floattime () - begin);
return 0;
}
And don't forget to wait some time before calculating time execution. Else, it will always return 0.00s.
Upvotes: 0