-
Notifications
You must be signed in to change notification settings - Fork 6
/
TimeSpec.cpp
93 lines (79 loc) · 2.86 KB
/
TimeSpec.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include "TimeSpec.h"
#include <iomanip>
#include <iostream>
#include <cassert>
// note: although C++11 finally provides nice initializer lists for
// structs we avoid them for reasons of backwards compatibility
const long TimeSpec::secInNsec = 1000 * 1000 * 1000;
TimeSpec::TimeSpec(const long secs, const long nsecs) : ts() {
assert(secs >= 0); // cannot handle negative times
assert(nsecs >= 0); // cannot handle negative times
ts.tv_sec = secs;
ts.tv_nsec = nsecs;
}
TimeSpec::TimeSpec(const double secs) : ts() {
assert(secs >= 0); // cannot handle negative times
ts.tv_sec = (long)(secs);
ts.tv_nsec = (long)(secs * secInNsec) % secInNsec;
}
double TimeSpec::seconds() const {
return (double)ts.tv_sec + (double)ts.tv_nsec / (double)secInNsec;
}
bool TimeSpec::operator==(const TimeSpec& other) const {
return (ts.tv_sec == other.ts.tv_sec) &&
(ts.tv_nsec == other.ts.tv_nsec);
}
bool TimeSpec::operator<(const TimeSpec& other) const {
if ( ts.tv_sec < other.ts.tv_sec ||
(ts.tv_sec == other.ts.tv_sec && ts.tv_nsec < other.ts.tv_nsec)) {
return true;
} else {
return false;
}
}
bool TimeSpec::operator>(const TimeSpec& other) const {
if ( ts.tv_sec > other.ts.tv_sec ||
(ts.tv_sec == other.ts.tv_sec && ts.tv_nsec > other.ts.tv_nsec)) {
return true;
} else {
return false;
}
}
TimeSpec TimeSpec::operator+(const TimeSpec& other) const {
const timespec ret = {ts.tv_sec + other.ts.tv_sec + (ts.tv_nsec + other.ts.tv_nsec) / secInNsec,
(ts.tv_nsec + other.ts.tv_nsec) % secInNsec};
return TimeSpec(ret);
}
TimeSpec& TimeSpec::operator+=(const TimeSpec& other) {
ts.tv_sec += other.ts.tv_sec + (ts.tv_nsec + other.ts.tv_nsec) / secInNsec;
ts.tv_nsec = (ts.tv_nsec + other.ts.tv_nsec) % secInNsec;
return *this;
}
TimeSpec TimeSpec::operator-(const TimeSpec& other) const {
if (ts.tv_nsec < other.ts.tv_nsec) {
const timespec ret = {ts.tv_sec - (other.ts.tv_sec + 1),
secInNsec + ts.tv_nsec - other.ts.tv_nsec};
assert(ret.tv_sec >= 0);
return TimeSpec(ret);
} else {
const timespec ret = {ts.tv_sec - other.ts.tv_sec,
ts.tv_nsec - other.ts.tv_nsec};
assert(ret.tv_sec >= 0);
return TimeSpec(ret);
}
}
TimeSpec& TimeSpec::operator-=(const TimeSpec& other) {
if (ts.tv_nsec < other.ts.tv_nsec) {
ts.tv_sec -= other.ts.tv_sec + 1;
ts.tv_nsec += secInNsec - other.ts.tv_nsec;
} else {
ts.tv_sec -= other.ts.tv_sec;
ts.tv_nsec -= other.ts.tv_nsec;
}
assert(ts.tv_sec >= 0);
return *this;
}
std::ostream& operator<<(std::ostream& os, const TimeSpec& ts) {
os << ts.ts.tv_sec << "." << std::setfill('0') << std::setw(9) << ts.ts.tv_nsec;
return os;
}