common.c

/** @file common.c
 *  @date April 24, 2009
 */

#include "common.h"
#include <sys/time.h>

/** The time the stopwatch was started. */
static struct timeval g_stopwatch_time;

/* ------------------------------------------------------------------------- */
int return_failure(const char * module, size_t line, int error)
{
    assert(NULL != module);

    /* Throw away full paths. */
    if (strchr(module, '\\') != NULL)
    {
        module = strrchr(module, '\\');
        assert(module != NULL);
        module++;
    }

    /* Print the module and line number. */
    fprintf(stderr, "%s(%d)", module, line);

    /* Print errno if possible. */
    if (error != 0)
    {
        fprintf(stderr, ": %s", strerror(error));
    }

    /* End the line and flush. */
    fprintf(stderr, "\n");

    /* This function always fails. */
    return EXIT_FAILURE;
}

/* ------------------------------------------------------------------------- */
void stopwatch_start(void)
{
    int result;

    result = gettimeofday(&g_stopwatch_time, NULL);
    assert(result == 0);
}

/* ------------------------------------------------------------------------- */
void stopwatch_stop(u_long filesize, size_t retries, u_long packets)
{
    struct timeval duration;
    struct timeval stop;
    int     ms;
    int     percent;
    int     speed;
    int     result;

    result = gettimeofday(&stop, NULL);
    assert(result == 0);

    /* Accuratly compute and normalize the duration. */
    duration.tv_sec = stop.tv_sec - g_stopwatch_time.tv_sec;
    duration.tv_usec = stop.tv_usec - g_stopwatch_time.tv_usec;
    while (duration.tv_usec < 0) {
        duration.tv_sec--;
        duration.tv_usec += 1000000;
    }

    /* Convert the duration unit to milliseconds. */
    ms = (int)((duration.tv_sec * 1000) + (duration.tv_usec / 1000));

    /* Compute the speed and percentage of packets lost. */
    speed = (ms == 0) ? 0 : filesize * 8 / ms;
    percent = retries * 100 / packets;

    /* Print out the statistics. */
    printf(
        "STATISTICS\n"
        "--------------------------------------------------\n"
        "  File size  (bytes):   %lu\n"
        "  Total time (ms):      %d\n"
        "  Speed      (kbps):    %d\n"
        "  Retries    (packets): %u (%d%%)\n"
        "--------------------------------------------------\n",
        filesize, ms, speed, retries, percent);
}
Valid HTML 4.01 Valid CSS