
/* getElapsedTime.c - portable code for querying accurate time */

#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# include <windows.h>  /* for QueryPerformanceCounter */
#else
# include <stdlib.h> /* for NULL */
# include <sys/time.h> /* for gettimeofday and struct timeval */
#endif

#ifdef _WIN32
static __int64 freq = 0;
#endif

#include "getElapsedTime.h"

double getElapsedTime()
{
    static int firstTime = 1;
    double secs;
#ifdef _WIN32
    /* Use Win32 performance counter for high-accuracy timing. */
    static __int64 startTime = 0;  /* Timer count for last fps update */
    __int64 newCount;

    if (!freq) {
        QueryPerformanceFrequency((LARGE_INTEGER*) &freq);
    }

    /* Update the frames per second count if we have gone past at least
    a second since the last update. */

    QueryPerformanceCounter((LARGE_INTEGER*) &newCount);
    if (firstTime) {
        startTime = newCount;
        firstTime = 0;
    }
    secs = (double) (newCount - startTime) / (double)freq;
#else
    /* Use BSD 4.2 gettimeofday system call for high-accuracy timing. */
    static struct timeval start_tp;
    struct timeval new_tp;

    gettimeofday(&new_tp, NULL);
    if (firstTime) {
        start_tp.tv_sec = new_tp.tv_sec;
        start_tp.tv_usec = new_tp.tv_usec;
        firstTime = 0;
    }
    secs = (new_tp.tv_sec - start_tp.tv_sec) + (new_tp.tv_usec - start_tp.tv_usec)/1000000.0;
#endif
    return secs;
}


