#1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2002
    Posts
    32
    Rep Power
    13

    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);
    }
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,643
    Rep Power
    4247
    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;
    }
  4. #3
  5. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2002
    Posts
    32
    Rep Power
    13
    the problem is i do need microsecond resolution... thanks anyway :)

IMN logo majestic logo threadwatch logo seochat tools logo