-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimer.cpp
73 lines (60 loc) · 1.26 KB
/
timer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include "prelude.h"
#ifdef _WIN32
#include <sys/timeb.h>
#include <sys/types.h>
void gettimeofday(struct timeval* t, void* timezone)
{
struct _timeb timebuffer;
_ftime(&timebuffer);
t->tv_sec = timebuffer.time;
t->tv_usec = 1000 * timebuffer.millitm;
}
#else
#include <sys/time.h>
#endif
Timer::Timer() { start(); }
Timer::~Timer() {}
inline double timeDiff(const timeval &t0, const timeval &t1)
{
double ms = (t1.tv_sec - t0.tv_sec) * 1000.0
+ (t1.tv_usec - t0.tv_usec) / 1000.0;
return ms;
}
void Timer::start()
{
gettimeofday(&init, NULL);
prev = init;
last_lap_duration = ellapsed_time_duration = 0.0;
isRunning = true;
}
// returns lap time in milliseconds
double Timer::lap()
{
if (!isRunning)
return 0.0;
timeval now;
gettimeofday(&now, NULL);
last_lap_duration = timeDiff(prev, now);
return last_lap_duration;
}
// returns total ellapsed time in milliseconds
double Timer::stop()
{
if (!isRunning)
return 0.0;
timeval now;
gettimeofday(&now, NULL);
last_lap_duration = timeDiff(prev, now);
ellapsed_time_duration = timeDiff(init, now);
isRunning = false;
return ellapsed_time_duration;
}
// re-retrieve values
double Timer::lastLap() const
{
return last_lap_duration;
}
double Timer::ellapsed() const
{
return ellapsed_time_duration;
}