//#include <stdio.h>
#include <time.h>

static double timeratio;
static int ftmp[2];
static int ttmp[2];

#ifdef __WATCOMC__

/* Get initial TSC value */
void rdtsc0();
#pragma aux rdtsc0 = 		\
" .586p "			\
" rdtsc "			\
" mov dword ptr ttmp[0],eax "	\
" mov dword ptr ttmp[4],edx " modify [eax edx];

/* Subtract initial TSC value, then convert to double */
double rdtsc();
#pragma aux rdtsc = 		\
" .586p "			\
" rdtsc "			\
" sub eax, ttmp[0]	 "	\
" sbb edx, ttmp[4]	 "	\
" mov dword ptr ftmp[0],eax "	\
" mov dword ptr ftmp[4],edx "	\
" fild qword ptr ftmp "		\
modify [eax edx] value [8087];

#else

/* Get initial TSC value */
static void rdtsc0() {
    _asm {
	rdtsc
        mov dword ptr ttmp[0],eax
        mov dword ptr ttmp[4],edx
    }
}

/* Subtract initial TSC value, then convert to double */
static double rdtsc() {
double ftmp;
    _asm {
	rdtsc
        sub eax, ttmp[0]	 
        sbb edx, ttmp[4]	 
        mov dword ptr ftmp[0],eax
        mov dword ptr ftmp[4],edx
        fild qword ptr ftmp
        fstp ftmp
    }
    return ftmp;
}

#endif

static int calibrated = 0;

static void calibrate() {
int t;
double t0;
    rdtsc0();

#if 1
    t = clock();
    while( clock() == t ) ;
    t0 = rdtsc();
    t = clock() + 4*CLOCKS_PER_SEC;
    while( clock()<t ) ;
    t0 = rdtsc() - t0;
#else
    t0 = 500*4000000.0;
#endif

    timeratio = 4.0/t0;

//    printf("\nMachine speed (clocks/second) = %10g Mhz\n\n",t0/4000000.0);

    calibrated = 1;
}

double second() {
    if( !calibrated ) calibrate();

    return rdtsc()*timeratio;
}

