Page 1 of 1

Comparing timeofday in C

Posted: Thu Sep 16, 2010 11:10 am
by Xephos
I haven't written in C in god knows how long and I have to use "timestamps" to find the travel time of a message from when I send it until I receive it again. For the life of me I cannot figure out how to get and compare the time of day in C so I can do this.

I also realize that a time of day function my not be the best solution for this, it was just a suggestion from the professor.

Any help would be sweet.

-X

Posted: Thu Sep 16, 2010 4:09 pm
by remagi

Code: Select all

#include <time.h>

int main(void)
{
    time_t     now;
    time_t     then;
    double     diff_in_seconds;

    then = time(NULL);

    /* do stuff here, event comes back */

    now = time(NULL);
    diff_in_seconds = difftime( now, then );
}




There are often substantially more efficient ways to access timers on a given platform, but if you want straight C, time_t and time() are the complete standard way.

On most platforms you can just subtract a time_t value from another, as they most often doubles, but difftime is the portable way.

-Remagi