rby1-sdk
Loading...
Searching...
No Matches
time_util.h
1#pragma once
2
3#include <chrono>
4#include <ctime>
5#include <iostream>
6
7#include "rby1-sdk/export.h"
8
9namespace rb {
10
11constexpr int64_t kNanosecondsInSecond = 1000000000;
12
20RBY1_SDK_API inline long GetDurationInNs(struct timespec start, struct timespec end) {
21 return (static_cast<int64_t>(end.tv_sec) * kNanosecondsInSecond + end.tv_nsec) -
22 (static_cast<int64_t>(start.tv_sec) * kNanosecondsInSecond + start.tv_nsec);
23}
24
32RBY1_SDK_API inline struct timespec GetDurationInTimespec(struct timespec start, struct timespec end) {
33 int64_t duration_ns = GetDurationInNs(start, end);
34
35 struct timespec duration{};
36
37 duration.tv_sec = duration_ns / kNanosecondsInSecond;
38 duration.tv_nsec = duration_ns % kNanosecondsInSecond;
39 return duration;
40}
41
50RBY1_SDK_API inline struct timespec GetCurrentTime() {
51 struct timespec current_time{};
52
53#ifdef __linux__
54 if (clock_gettime(CLOCK_MONOTONIC, &current_time) != 0) {
55 std::cerr << "Failed to get current time" << std::endl;
56 }
57#else
58 auto ct = std::chrono::steady_clock::now();
59 int64_t ct_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(ct.time_since_epoch()).count();
60 current_time.tv_sec = ct_ns / kNanosecondsInSecond;
61 current_time.tv_nsec = ct_ns % kNanosecondsInSecond;
62#endif
63
64 return current_time;
65}
66
73RBY1_SDK_API inline int64_t TimespecInNs(const struct timespec& ts) {
74 return static_cast<int64_t>(ts.tv_sec) * kNanosecondsInSecond + static_cast<int64_t>(ts.tv_nsec);
75}
76
83RBY1_SDK_API inline struct timespec TimepointToTimespec(
84 std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds> tp) {
85 using namespace std::chrono;
86
87 auto secs = time_point_cast<seconds>(tp);
88 auto ns = time_point_cast<nanoseconds>(tp) - time_point_cast<nanoseconds>(secs);
89
90 return timespec{secs.time_since_epoch().count(), static_cast<long>(ns.count())};
91}
92
99RBY1_SDK_API inline double TimespecToDouble(const struct timespec& ts) {
100 return static_cast<double>(TimespecInNs(ts)) / static_cast<double>(kNanosecondsInSecond);
101}
102
112RBY1_SDK_API inline timespec NormalizeTimespec(timespec ts) {
113 ts.tv_sec += ts.tv_nsec / kNanosecondsInSecond;
114 ts.tv_nsec %= kNanosecondsInSecond;
115 return ts;
116}
117
118class RBY1_SDK_API TimeWatch {
119 public:
120 TimeWatch() : ts_(GetCurrentTime()) {}
121
122 void Record() { ts_ = GetCurrentTime(); }
123
124 long GetDurationInNs(bool record = false) {
125 const auto& cts = GetCurrentTime();
126 const auto& duration = rb::GetDurationInNs(ts_, cts);
127 if (record) {
128 ts_ = cts;
129 }
130 return duration;
131 }
132
133 private:
134 struct timespec ts_;
135};
136
137} // namespace rb
Definition time_util.h:118