September 9th, 2002, 07:28 AM
-
computing time elapsed in C?
ok i looked thru the glibc manual and found the timeval struct... the code i've come up with is below... please let me know if i'm correct
Code:
/**
* this function is for computing the time difference between timeval x and y
* the result is stored in result
*/
int
timeval_subtract (struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
tv_usec is certainly positive. */
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
struct timeval start, stop, echodelay; // start, stop and echo delay times
if((gettimeofday(&start, NULL)) == -1)
{
perror("gettimeofday");
exit(1);
}
// do stuff
if((gettimeofday(&stop, NULL)) == -1)
{
perror("gettimeofday");
exit(1);
}
/* compute time delay */
timeval_subtract(&echodelay, &stop, &start);
printf("Echo delay is %ds and %dus\n", echodelay.tv_sec, echodelay.tv_usec);
}
September 9th, 2002, 01:21 PM
-
If you don't care about microsecond level time, you can possibly use difftime().
Code:
#include <time.h>
int main(int argc, char *argv[]) {
time_t start, stop;
double diff
start = time(NULL);
// Do stuff
stop = time(NULL);
diff = difftime(start, stop);
printf("Difference is %e\n", diff);
return 0;
}
September 10th, 2002, 06:30 AM
-
the problem is i do need microsecond resolution... thanks anyway :)