#include "V.h"
#include "pktime.h"
static char SCCS_pktime[] = "@(#)pktime 14/04/23";
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* This is a timing module. It contains a couple of useful routines for getting *
* various time intervals as floating-point values.                             *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
TIMV time0={0}, timei={0}, time1={0};    /* For timing packets */
TIMZ timez={0};
double timint=0.0;	/* Last-measured interval, global for debugging */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* This routine times the interval between its calls; it is used to get the *
* intervals  between successive sent and/or received packets.  It uses the *
* global timestamps above for its memory.                                  *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
double pktime()
{
	Fenter("pktime");
	gettimeofday(&time1,&timez);
	V6 "time0=(%08X,%08X) time1=(%08X,%08X)",
		time0.tv_sec,time0.tv_usec,time1.tv_sec,time1.tv_usec D;
	if (time0.tv_sec == 0) {	/* This happens with initial messages */
		time0.tv_sec = time1.tv_sec;
		time0.tv_usec = time1.tv_usec;
	}
	timei.tv_sec = time1.tv_sec  - time0.tv_sec;
	timei.tv_usec = time1.tv_usec - time0.tv_usec;
	while (timei.tv_usec < 0) {
		timei.tv_sec  -= 1;
		timei.tv_usec += 1000000;
	}
	timint = (double)timei.tv_sec + ((double)timei.tv_usec * 0.000001);
	V6 "timint: %08X %08X %8.3f",timint,timint,timint D;
	V5 "time0=(%08X,%08X) time1=(%08X,%08X) timint=%08X %08X",
		time0.tv_sec,time0.tv_usec,time1.tv_sec,time1.tv_usec,timint D;
	time0 = time1;		/* Note time for next message */
	Fexit;
	return(timint);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Calculate the time interval between two calls.  The first arg receives the *
* current timestamp;  the return value is the difference between the new and *
* old timestamps.  To initialize, call it with old null.                     *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
double pktint(new,old)
	TIMV *new;	/* Gets new timestamp */
	TIMV *old;	/* Old timestamp for differences */
{	TIMV  tint;

	Fenter("pkint");
	gettimeofday(new,&timez);
	if (!old) Fail;
	if (old->tv_sec == 0) {
		old->tv_sec = new->tv_sec;
		old->tv_usec = new->tv_usec;
		Fail;
	}
	tint.tv_sec = new->tv_sec  - old->tv_sec;
	tint.tv_usec = new->tv_usec - old->tv_usec;
	while (tint.tv_usec < 0) {
		tint.tv_sec  -= 1;
		tint.tv_usec += 1000000;
	}
	timint = (double)tint.tv_sec + ((double)tint.tv_usec * 0.000001);
fail:
	Fexit;
	return(timint);
}
