How can I use gettimeofday to measure the passage of time?

244 Views Asked by At

I'm only allowed to use this function and I'm trying to figure out a way to calculate time elapsed, any ideas? I'm confused..

# include <sys/types.h>
# include <sys/time.h>
# include <stdio.h>
# include <unistd.h>


int main(int argc, char* argv[])
{
    struct timeval now;
    struct timeval start;
    int t_now;
    int t_stop;
    int t_start;
    int i;

    gettimeofday(&start, NULL);
    t_start = start.tv_usec / 1000;
    t_stop = t_start + 200;

    while (42)
    {
        usleep(2000);
        gettimeofday(&now, NULL);
        t_now = now.tv_usec / 1000;
        if (t_now - t_stop > -1)
        {
            break;
        }
        printf ("%d\n", t_now);
        usleep(2000);
    }
    return 0;
}

I was doing this but it will keep looping, and won't stop..

1

There are 1 best solutions below

5
pm100 On

this

t_start = start.tv_usec / 1000;

isnt doing what you expect. tv_usec only has fractions of a second, you need

long long msec = (start.tv_sec * 1000) + start.tv_usec/1000;

to get total msec