#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
#include <stdint.h>
#include <limits.h>
#include <sys/time.h>
#include "../lve-ctl.h"

#define DIFF_T(a,b) ( (a.tv_sec - b.tv_sec) + (double)(a.tv_usec - b.tv_usec)/1000000 )

static int lve_available = 0; /* not available by default */
struct liblve *lve;

/**
 * Default will have 5000 entry
 * You can change it by providing parameter
 * First parameter controls number of lve re-entrie
 * Author: Igor Seletskiy <iseletsk@gmail.com>
 */

main(int argc, char *argv[]) 
{
  int i,j,k,x;
  uint32_t p_cookie;  
  int rc;
  struct timeval start, end;
  
  int entries = 5000;
  if (argc>1) {
    entries = atoi(argv[1]);
    argc--;
  }
  printf("Entries %d\n", entries);
  
  rc = lve_instance_init(NULL);
  printf("LVE data size %d\n", rc);
  lve = malloc(rc);
  rc = lve_instance_init(lve);
  if (rc != 0) {
    printf("Can't init lve instance %d\n", rc);
    _exit(-1);
  }
  printf("Successfull init lve instance %d - %d\n", rc, getpid());
  


  // entering into same LVE each time
  for (i = 0; i < 10; i++) {
    gettimeofday(&start, NULL);
    for (x=0; x<entries; x++) {
      if (lve_enter(lve, 900, -1, -1, &p_cookie)) {
	exit(-1);
      }
      if (lve_leave(lve, &p_cookie)) {
	printf("lve_leave failed");
	exit(-1);
      }
    }
    gettimeofday(&end, NULL);
    printf("lve%d re-entry - time took %.6f sec, avg: %.6f\n", i, 
	   DIFF_T(end, start), DIFF_T(end, start)/entries);
  }

  // no lve
  for (i = 0; i < 10; i++) {
    gettimeofday(&start, NULL);
    for (x=0; x<entries; x++) {
      k = x*x;
    }
    gettimeofday(&end, NULL);
    printf("Without lve%d - time took %.6f sec\n", i, DIFF_T(end,start));
  }

  lve_instance_destroy(lve);

}
