libxr  1.0
Want to be the best embedded framework
Loading...
Searching...
No Matches
monotonic_time.hpp
1#pragma once
2
3#include <time.h>
4
5#include <cstdint>
6
7namespace LibXR
8{
9namespace MonotonicTime
10{
11
12inline timespec NowSpec()
13{
14 timespec ts = {};
15 clock_gettime(CLOCK_MONOTONIC, &ts);
16 return ts;
17}
18
19inline uint64_t NowMilliseconds()
20{
21 const timespec ts = NowSpec();
22 return static_cast<uint64_t>(ts.tv_sec) * 1000ULL +
23 static_cast<uint64_t>(ts.tv_nsec) / 1000000ULL;
24}
25
26inline timespec RelativeFromMilliseconds(uint32_t milliseconds)
27{
28 timespec ts = {};
29 ts.tv_sec = static_cast<time_t>(milliseconds / 1000U);
30 ts.tv_nsec = static_cast<long>(milliseconds % 1000U) * 1000000L;
31 return ts;
32}
33
34inline timespec AddMilliseconds(timespec base, uint64_t milliseconds)
35{
36 base.tv_sec += static_cast<time_t>(milliseconds / 1000ULL);
37 base.tv_nsec += static_cast<long>(milliseconds % 1000ULL) * 1000000L;
38 if (base.tv_nsec >= 1000000000L)
39 {
40 base.tv_sec += base.tv_nsec / 1000000000L;
41 base.tv_nsec %= 1000000000L;
42 }
43 return base;
44}
45
46inline uint32_t RemainingMilliseconds(uint64_t deadline_ms)
47{
48 const uint64_t now_ms = NowMilliseconds();
49 if (now_ms >= deadline_ms)
50 {
51 return 0;
52 }
53 return static_cast<uint32_t>(deadline_ms - now_ms);
54}
55
56inline int64_t ElapsedMicroseconds(const timespec& start)
57{
58 const timespec now = NowSpec();
59 return static_cast<int64_t>(now.tv_sec - start.tv_sec) * 1000000LL +
60 static_cast<int64_t>(now.tv_nsec - start.tv_nsec) / 1000LL;
61}
62
63inline uint32_t WaitSliceMilliseconds(uint32_t remaining_ms)
64{
65 return remaining_ms;
66}
67
68} // namespace MonotonicTime
69} // namespace LibXR
LibXR 命名空间
Definition ch32_can.hpp:14