timehelp.c

/*
 * File Name:     timehelp.c
 * Author:        Jade Cheng
 * Date:          March 29, 2009
 * Course:        ICS 451
 * Assignment:    Project 2
 */

#include "common.h"
#include "timehelp.h"

static timeval time_normalize(timeval tv);

/* ------------------------------------------------------------------------ */
extern timeval time_add(timeval time1, timeval time2)
{
    timeval tv;

    /* Normalize the result from the addition and return it. */
    tv.tv_sec = time1.tv_sec + time2.tv_sec;
    tv.tv_usec = time1.tv_usec + time2.tv_usec;
    return time_normalize(tv);
}

/* ------------------------------------------------------------------------ */
extern int time_cmp(timeval time1, timeval time2)
{
    /* Don't trust the times coming in. */
    time1 = time_normalize(time1);
    time2 = time_normalize(time2);

    /* Returns something like strcmp. */
    if (time1.tv_sec > time2.tv_sec)
        return 1;
    if (time1.tv_sec < time2.tv_sec)
        return -1;
    if (time1.tv_usec > time2.tv_usec)
        return 1;
    if (time1.tv_usec < time2.tv_usec)
        return -1;
    return 0;
}

/* ------------------------------------------------------------------------ */
extern timeval time_now(void)
{
    timeval tv;

    gettimeofday(&tv, NULL);
    return tv;
}

/* ------------------------------------------------------------------------ */
extern timeval time_seconds(int seconds)
{
    timeval tv;

    tv.tv_sec = seconds;
    tv.tv_usec = 0;
    return tv;
}

/* ------------------------------------------------------------------------ */
extern timeval time_sub(timeval time1, timeval time2)
{
    timeval tv;

    /* Normalize the result from the subtraction and return it. */
    tv.tv_sec = time1.tv_sec - time2.tv_sec;
    tv.tv_usec = time1.tv_usec - time2.tv_usec;
    return time_normalize(tv);
}

/* ------------------------------------------------------------------------ */
/**
 * Normalizes and returns a time value.  A normalized time value is a time
 * value with 0 <= microseconds <= 1000000.
 *
 * @param tv The source time value.
 *
 * @return A normalized time value.
 */
static timeval time_normalize(timeval tv)
{
    while (tv.tv_usec < 0) {
        tv.tv_usec += 1000000;
        tv.tv_sec--;
    }

    while (tv.tv_usec > 1000000) {
        tv.tv_usec -= 1000000;
        tv.tv_sec++;
    }

    return tv;
}
Valid HTML 4.01 Valid CSS