#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#include <unistd.h>

#define NSTRS     1
#define ADDRESS   "mysocket"
#define CPS   199434188
#define CPMS  199.434188

#define NUMIPC    1
#define NUMLOOP 10000

#define NUMTRIES 20

static  double d;
static  int it;
/*
 * String we send to server.
 */
char *strs[NSTRS] = {
  "R"
};

static inline void
rk_rdtsc(unsigned long long *data_p)
{
  __asm __volatile(
		   "rdtsc"
		   :"=a"(*(int *)(data_p)), "=d"(*(((int *)data_p)+1))
		   :
		   :"eax","edx");
}


void
compute_long(int iteration){

  int j, i;

  for(j=0; j < NUMLOOP ; j++){
    for(i=0; i < iteration; i++){
      d = iteration;
      d = d*30;
      d = d/10.0;
      d = d/3.1;
      it = iteration;
      it = it - it*it;
      it = it/(iteration+1);
    }
    //usleep(1);
  }
}

  
int
main()
{
  char c;
  FILE *fp;
  register int i, s, len;
  struct sockaddr_un saun;

  unsigned long long start, end;
  double elapsed;

  if((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0){
    perror("client: socket");
    exit(1);
  }
  
  saun.sun_family = AF_UNIX;
  strcpy(saun.sun_path, ADDRESS);

  len = sizeof(saun.sun_family) + strlen(saun.sun_path);
  
  if(connect(s, &saun, len) < 0){
    perror("client: connect");
    exit(1);
  }

  fp = fdopen(s, "r");

  /* warm up.. */
  rk_rdtsc(&start);
  rk_rdtsc(&end);
  start = end = elapsed = 0;
  
  if(fork()==0){
    int i;
    for(i=0;i<50;i++){
      compute_long(100);
      sleep(1);
    }

    exit(1);
  }
  else{
    sleep(1);

    for(i=0; i<NUMTRIES; i++){
      if(i==5)
	rk_rdtsc(&start);  
      send(s, strs[0], strlen(strs[0]), 0);
      c= fgetc(fp);
    }
    
    rk_rdtsc(&end);  
    elapsed = (double)(end-start)/(CPS);
    printf("%f cycles (%f sec on 200Mhz machine) for %d IPC [avg=%f sec]\n", 
	   (double)(end-start), (double)(elapsed), NUMTRIES, elapsed/(NUMTRIES-5));
    while(1)
      sleep(10);
    exit(0);
  }
}

