#include <sys/time.h>
#include <ctime>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include "Platform.h"
#include "Watch.h"
using namespace std;
#ifdef __MACH__
#include <sys/time.h>
//clock_gettime is not implemented on OSX
int clock_gettime(int /*clk_id*/, struct timespec* t) {
struct timeval now;
int rv = gettimeofday(&now, NULL);
if (rv) return rv;
t->tv_sec = now.tv_sec;
t->tv_nsec = now.tv_usec * 1000;
return 0;
}
//CLOCK_REALTIME is not defined on OSX
#define CLOCK_REALTIME 0
#endif
Watch::Watch(void)
{
Reset();
}
void Watch::Start() {
//_startTime = GetTime();
clock_gettime(CLOCK_REALTIME,&_startTime);
_isRunning = true;
}
void Watch::Stop() {
//_stopTime = GetTime();
clock_gettime(CLOCK_REALTIME,&_stopTime);
_isRunning = false;
}
void Watch::Reset(){
struct timespec reset = {0,0};
_startTime = _stopTime = reset;
_isRunning = false;
}
// Get elapsed time in millisec
long Watch::GetElapsedTime(){
if(_isRunning){
struct timespec now;
clock_gettime(CLOCK_REALTIME,&now);
return diff(_startTime, now);
}
return diff(_startTime,_stopTime);
}
inline long diff(timespec t1, timespec t2)
{
return (t2.tv_sec-t1.tv_sec)*1000 + (t2.tv_nsec-t1.tv_nsec)/1000000;
}
/*
inline long Watch::GetTime() {
//struct _timeb t;
//ftime(&t);
//return int(t.time * 1000 + t.millitm);
struct timespec ts;
clock_gettime(CLOCK_REALTIME,&ts);
printf("ts.tv_sec=%d\n", ts.tv_sec);
printf("ts.tv_nsec=%d\n", ts.tv_nsec);
return long(ts.tv_sec*1000 + ts.tv_nsec/1000000);
//return clock()*1000/CLOCKS_PER_SEC;
}
*/