forked from uva-cs/pdr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimer.cpp
64 lines (56 loc) · 1.37 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
#include <sstream>
#include <math.h>
#include <cstring>
#include "timer.h"
timer::timer(timer & t) : running(t.running) {
memcpy(&startVar, &(t.startVar), sizeof (timeval));
memcpy(&stopVar, &(t.stopVar), sizeof (timeval));
}
int timer::start() {
if (!running) {
running = true;
gettimeofday(&startVar,NULL);
return 0;
}
return 1;
}
int timer::stop() {
if (running) {
running = 0;
gettimeofday(&stopVar,NULL);
return 0;
}
return 1;
}
ostream & timer::print(ostream & out) {
return (out << toString());
}
double timer::getTime() {
time_t sec = stopVar.tv_sec - startVar.tv_sec;
long usec = stopVar.tv_usec - startVar.tv_usec;
return sec + usec/1000000.0;
}
string timer::toString() {
ostringstream out;
if (running)
out << "Timer still running\n";
else {
time_t sec = stopVar.tv_sec - startVar.tv_sec;
long usec = stopVar.tv_usec - startVar.tv_usec;
if ( usec < 0 ) {
sec--;
usec += 1000000;
}
out << sec << "."
<< ((usec<100000)?"0":"")
<< ((usec<10000)?"0":"")
<< ((usec<1000)?"0":"")
<< ((usec<100)?"0":"")
<< ((usec<10)?"0":"")
<< usec;
}
return out.str();
}
ostream & operator<<(ostream &out, timer &t) {
return t.print(out);
}