#include <stdio.h>
#include <stdlib.h>

#if defined(WIN32) || defined(WIN64)
  #include <windows.h>
  #include <sys\Timeb.h>
#else
  #include <sys/resource.h>
  #include <time.h>
  #include <sys/times.h>
#endif

#include "ProcessTime.h"

#if defined(WIN32) || defined(WIN64)

static float time(LPFILETIME t) {
  double ft = (t->dwHighDateTime*4294967296.0+t->dwLowDateTime)/10000000.0;
  return((float) ft);
/*  ULARGE_INTEGER _time;
  _time.LowPart = t->dwLowDateTime;
  _time.HighPart = t->dwHighDateTime;
  return((float) (((signed size_t)(_time.QuadPart))/10000000.0));*/
}

float getProcessTimes(void) {
  FILETIME creationTimef,exitTimef,kernelTimef,userTimef;
  GetProcessTimes(GetCurrentProcess(),&creationTimef,&exitTimef,&kernelTimef,&userTimef);
  return(time(&kernelTimef)+time(&userTimef));
}

float diffTime(_timeb *tbf,_timeb *tbi) {
  float dt = 0;
  dt =(float) (tbf->time-tbi->time);
  float mls = (tbf->millitm-tbi->millitm)/1000.0F;
  return(dt+mls);
}

#else

float getProcessTimes(void) {
  struct rusage t;
  getrusage(RUSAGE_SELF,&t);
  float tf = t.ru_utime.tv_sec+(t.ru_utime.tv_usec/1000000.0F)+
             t.ru_stime.tv_sec+(t.ru_stime.tv_usec/1000000.0F);
  return(tf);
}

double getUnixClock(void) {
  struct timeval t;
  gettimeofday(&t,NULL);
  return(t.tv_sec+(t.tv_usec/1000000.0));
}

#endif
