-
Notifications
You must be signed in to change notification settings - Fork 3
/
quantum_waiter.h
47 lines (42 loc) · 1.45 KB
/
quantum_waiter.h
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
#ifndef _QUANTUM_WAITER_H_
#define _QUANTUM_WAITER_H_
#include <sys/timerfd.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
class QuantumWaiter {
public:
QuantumWaiter(int interval_us) : timer_fd_(-1), interval_us_(interval_us) {}
void WaitNextQuantum() {
if (timer_fd_ == -1) {
struct itimerspec new_value;
if (clock_gettime(CLOCK_REALTIME, &new_value.it_value) != 0) {
fprintf(stderr, "clock_gettime failed\n");
abort();
}
new_value.it_interval.tv_sec = interval_us_ / 1000000;
new_value.it_interval.tv_nsec = interval_us_ % 1000000 * 1000;
timer_fd_ = timerfd_create(CLOCK_REALTIME, 0);
if (timer_fd_ == -1) {
fprintf(stderr, "timerfd_create failed\n");
abort();
}
if (timerfd_settime(timer_fd_, TFD_TIMER_ABSTIME, &new_value, NULL) != 0) {
fprintf(stderr, "timerfd_settime failed\n");
abort();
}
}
uint64_t val;
if (read(timer_fd_, &val, sizeof(uint64_t)) != sizeof(uint64_t)) {
fprintf(stderr, "Failed to read from timer\n");
abort();
}
// if (val > 1) {
// fprintf(stderr, "[QuantumWaiter interval=%d] miss %d quanta\n",
// interval_us_, (int)(val-1));
// }
}
int timer_fd_;
int interval_us_;
};
#endif