zpp
Zephyr C++20 Framework
clock.hpp
Go to the documentation of this file.
1 //
2 // Copyright (c) 2019 Erwin Rol <erwin@erwinrol.com>
3 //
4 // SPDX-License-Identifier: Apache-2.0
5 //
6 
7 #ifndef ZPP_INCLUDE_ZPP_CLOCK_HPP
8 #define ZPP_INCLUDE_ZPP_CLOCK_HPP
9 
10 #include <zephyr/kernel.h>
11 #include <zephyr/sys_clock.h>
12 #include <zephyr/sys/__assert.h>
13 
14 #include <chrono>
15 #include <limits>
16 
17 namespace zpp {
18 
22 class uptime_clock {
23 public:
24  using rep = int64_t;
25  using period = std::nano;
26  using duration = std::chrono::duration<rep, period>;
27  using time_point = std::chrono::time_point<uptime_clock>;
28  static constexpr bool is_steady = false;
29 
35  static time_point now() noexcept
36  {
37  return time_point(duration(k_ticks_to_ns_floor64(k_uptime_ticks())));
38  }
39 };
40 
41 
45 class cycle_clock {
46 public:
47  using rep = uint64_t;
48  using period = std::nano;
49  using duration = std::chrono::duration<rep, period>;
50  using time_point = std::chrono::time_point<cycle_clock>;
51  static constexpr bool is_steady = false;
52 
58  static time_point now() noexcept
59  {
60  return time_point(duration(k_cyc_to_ns_floor64(k_cycle_get_32())));
61  }
62 };
63 
71 template<class T_Rep, class T_Period>
72 constexpr k_ticks_t to_tick(const std::chrono::duration<T_Rep, T_Period>& d) noexcept
73 {
74  using namespace std::chrono;
75 
76  return k_ns_to_ticks_floor64(duration_cast<nanoseconds>(d).count());
77 }
78 
79 
87 template<class T_Rep, class T_Period>
88 constexpr k_timeout_t to_timeout(const std::chrono::duration<T_Rep, T_Period>& d) noexcept
89 {
90  return { to_tick(d) };
91 }
92 
93 } // namespace zpp
94 
95 #endif // ZPP_INCLUDE_ZPP_CLOCK_HPP
Clock representing the system’s hardware clock.
Definition: clock.hpp:45
static time_point now() noexcept
Get current cycle count.
Definition: clock.hpp:58
std::chrono::duration< rep, period > duration
Definition: clock.hpp:49
static constexpr bool is_steady
Definition: clock.hpp:51
std::chrono::time_point< cycle_clock > time_point
Definition: clock.hpp:50
std::nano period
Definition: clock.hpp:48
uint64_t rep
Definition: clock.hpp:47
Clock measuring elapsed time since the system booted.
Definition: clock.hpp:22
static constexpr bool is_steady
Definition: clock.hpp:28
std::chrono::duration< rep, period > duration
Definition: clock.hpp:26
std::chrono::time_point< uptime_clock > time_point
Definition: clock.hpp:27
int64_t rep
Definition: clock.hpp:24
static time_point now() noexcept
Get current uptime.
Definition: clock.hpp:35
std::nano period
Definition: clock.hpp:25
constexpr k_timeout_t to_timeout(const std::chrono::duration< T_Rep, T_Period > &d) noexcept
convert a duration to tick
Definition: clock.hpp:88
constexpr k_ticks_t to_tick(const std::chrono::duration< T_Rep, T_Period > &d) noexcept
convert a duration to tick
Definition: clock.hpp:72