/**********************************************************
 * exampleUnixTime -  this program illustrates how to obtain
*    a Unix timestamp, how to compute a RTT, and how to print 
*    a timestamp as a human readable string.
*
* Notes:
*  -to build, just issue 'gcc exampleUnixTime.c'
*
* Revisions
*
 **************************************************************/
#include <stdio.h>
#include <stdlib.h>     /* for atoi() and exit() */
#include <sys/time.h>
#include <string.h>     /* for memset() */
#include <signal.h>
#include <errno.h>


void signal_handler();
double getTime();
void printCurTime(char *bufPtr);

int main(int argc, char *argv[])
{
  double time = 0.0;
  struct sigaction sig;
  int loopCount = 100000000;
  int i;
  int j;
//  double j;
  char tmpLine[64];

  /* setup signals */
  memset(&sig,0,sizeof(sig));
  sig.sa_handler = signal_handler;
  sigaction (SIGINT,  &sig, NULL);
  sigaction (SIGALRM, &sig, NULL);
	
  while (1) 
  {
		 
    alarm(2);
    j=1024;
    time = getTime();
    for (i=0;i<loopCount;i++) {
      j += i / 1.1;
    }
    alarm(0);
    time = getTime() - time;	
    printCurTime(tmpLine);
    printf("%s: observed delay :  %3.6f seconds \n",tmpLine,time);
  }     

  exit(0);
}

double getTime()
{
	struct timeval curTime;
	(void) gettimeofday (&curTime, (struct timezone *) NULL);
	return (((((double) curTime.tv_sec) * 1000000.0) 
             + (double) curTime.tv_usec) / 1000000.0); 
}

void printCurTime(char *tmpLine)
{
struct timeval curTime;


  (void) gettimeofday(&curTime, (struct timezone *)0);
  sprintf(tmpLine,"%s ",  (char *)ctime((const long int *)&curTime));
  //remove the CR that ctime adds
  tmpLine[strlen(tmpLine)-2] = 0x0;
  tmpLine[strlen(tmpLine)-1] = 0x0;
//  printf(tmpLine);
}

void signal_handler(int sig) {
	switch(sig) {
		case SIGINT:
            printf("SIGINT - EXIT PROGRAM \n");
            exit(0);
            break;
		case SIGALRM:
            printf("ALARM - EXIT PROGRAM \n");
            exit(0);
			break;
	}
}


