
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/mman.h>
#include "vgasync.h"
#include "rtctimer.h"
#include "vidmode.h"

static int timediff( struct timeval *large, struct timeval *small )
{
    return (   ( ( large->tv_sec * 1000 * 1000 ) + large->tv_usec )
             - ( ( small->tv_sec * 1000 * 1000 ) + small->tv_usec ) );
}

int main( int argc, char **argv )
{
    struct timeval start;
    struct timeval end;
    int total = 0;
    int num = 500;
    int i;
    double perrefresh, refresh;
    vidmode_t *vm;

    vm = vidmode_new();
    if( !vm ) {
        char *disp = getenv( "DISPLAY" );
        if( !disp ) disp = "";
        fprintf( stderr, "vidinfo: Can't get info for display '%s'.\n", disp );
    } else {
        fprintf( stderr, "vidinfo: Printing mode information.\n" );
        vidmode_print_modeline( vm );
        vidmode_delete( vm );
    }

    setpriority( PRIO_PROCESS, 0, -19 );
    set_realtime_priority( 0 );

    vgasync_init();

    vgasync_spin_while_refresh();
    gettimeofday( &start, 0 );

    for( i = 0; i < num; i++ ) {
        vgasync_spin_while_refresh();
        gettimeofday( &end, 0 );
        total += timediff( &end, &start );
        gettimeofday( &start, 0 );
    }
    perrefresh = (((double) total) / ((double) num));
    refresh = 1000000.0 / perrefresh;
    fprintf( stderr, "Average time per refresh is %f usec, so refresh rate is %fhz.\n",
             perrefresh, refresh );

    return 0;
}

