-
Notifications
You must be signed in to change notification settings - Fork 2
/
Timer.cpp
78 lines (62 loc) · 2.07 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
74
75
76
77
// SPDX-FileCopyrightText: 2018 Lutz Freitag
// SPDX-License-Identifier: MIT
#include "Timer.h"
#include <cstring>
#include <time.h>
#include <stdexcept>
#include <cerrno>
#include <string>
namespace simplyfile {
namespace {
void normalize(struct timespec& time) {
while (time.tv_nsec > 1000000000) {
time.tv_nsec -= 1000000000;
time.tv_sec += 1;
}
while (time.tv_nsec < -1000000000) {
time.tv_nsec += 1000000000;
time.tv_sec -= 1;
}
}
}
Timer::Timer(int flags)
: FileDescriptor(::timerfd_create(CLOCK_MONOTONIC, flags))
{}
Timer::Timer(std::chrono::nanoseconds duration, bool oneShot, int flags)
: FileDescriptor(::timerfd_create(CLOCK_MONOTONIC, flags))
{
reset(duration, oneShot);
}
int Timer::getElapsed() const {
uint64_t elapsed {0};
::read(*this, &elapsed, sizeof(elapsed));
return elapsed;
}
void Timer::cancel() {
struct itimerspec new_value{};
if (timerfd_settime(*this, TFD_TIMER_ABSTIME, &new_value, NULL) == -1) {
throw std::runtime_error("cannot cancel timer " + std::string(strerror(errno)));
}
}
void Timer::reset(std::chrono::nanoseconds duration, bool oneShot) {
cancel();
struct itimerspec new_value {};
struct timespec now;
if (clock_gettime(CLOCK_MONOTONIC, &now) == -1) {
throw std::runtime_error("cannot get the current time");
}
int64_t seconds = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
int64_t nanoSeconds = std::chrono::duration_cast<std::chrono::nanoseconds>(duration - std::chrono::seconds(seconds)).count();
new_value.it_value.tv_sec = now.tv_sec + seconds;
new_value.it_value.tv_nsec = now.tv_nsec + nanoSeconds;
normalize(new_value.it_value);
if (not oneShot) {
new_value.it_interval.tv_sec = seconds;
new_value.it_interval.tv_nsec = nanoSeconds;
normalize(new_value.it_interval);
}
if (timerfd_settime(*this, TFD_TIMER_ABSTIME, &new_value, NULL) == -1) {
throw std::runtime_error("cannot set timeout for timerfd " + std::string(strerror(errno)));
}
}
}