Sound Byte Libs 0.5.1-340-gab5b79a
C++ firmware library for audio applications on 32-bit ARM Cortex-M processors
Loading...
Searching...
No Matches
cycles.hpp
Go to the documentation of this file.
1/**
2 * @file cycles.hpp
3 * @brief The cycle counter behind the profiling tools
4 *
5 * Provides sbl::system::profiling::{init, cycles, cycle_rate, CycleScope}
6 * over the target's cycle port: the MCU directory's system/port/cycles.hpp,
7 * reached by include path (DWT CYCCNT on the STM32H7, CLOCK_MONOTONIC in
8 * nanoseconds on the host). The contract is cycles_requirements.hpp.
9 *
10 * A cycle is one count of that counter; cycle_rate() is counts per second.
11 */
12
13#ifndef SBL_SYSTEM_PROFILING_CYCLES_HPP_
14#define SBL_SYSTEM_PROFILING_CYCLES_HPP_
15
16#include <cstdint>
17#include <sbl/system/port/cycles.hpp>
19
20namespace sbl::system::profiling {
21
22static_assert(port::cycles_port_valid<sbl::driver::Cycles>,
23 "SBL ERROR: the target's cycle port does not meet its contract");
24
25/** Start the counter. Call once at startup, after clock configuration. */
26inline void init() { sbl::driver::Cycles::init(); }
27
28/**
29 * init() in a build with SBL_PROFILING and nothing otherwise, for an app
30 * whose measurements are all gated by it.
31 */
32inline void init_for_profiling() {
33#ifdef SBL_PROFILING_ENABLED
34 init();
35#endif
36}
37
38/** The current count (free-running, wraps at 2^32). */
39inline uint32_t cycles() { return sbl::driver::Cycles::read(); }
40
41/** Counts per second. */
42inline constexpr uint32_t cycle_rate() { return sbl::driver::Cycles::rate(); }
43
44/**
45 * RAII scope that measures a block of code in cycles.
46 * Usage: volatile uint32_t elapsed; { CycleScope s(elapsed); ... }
47 */
48struct CycleScope {
49 uint32_t start_;
50 volatile uint32_t& result_;
51
52 explicit CycleScope(volatile uint32_t& out) : start_(cycles()), result_(out) {}
53 ~CycleScope() { result_ = cycles() - start_; }
54};
55
56} // namespace sbl::system::profiling
57
58#endif // SBL_SYSTEM_PROFILING_CYCLES_HPP_
The cycle port: what the profiling tools need from a target.
Profiling: the cycle counter, the audio budget, section profiles and reports.
constexpr uint32_t cycle_rate()
Definition cycles.hpp:42