From 42273480515d9f431f158e9826be209501591a06 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 24 Nov 2026 02:46:25 +0300 Subject: [PATCH] feat(Time): add MonotonicClock/CivilClock/ManualClock and bounded Stopwatch (M-TIME-02) --- include/Void/Time/Clock.hpp | 210 ++++++++++++++++++++++++++++ include/Void/Time/Stopwatch.hpp | 150 ++++++++++++++------ tests/standalone/Time/Clock.cpp | 101 +++++++++++++ tests/standalone/Time/Stopwatch.cpp | 55 ++++++++ 4 files changed, 471 insertions(+), 45 deletions(-) create mode 100644 include/Void/Time/Clock.hpp create mode 100644 tests/standalone/Time/Clock.cpp diff --git a/include/Void/Time/Clock.hpp b/include/Void/Time/Clock.hpp new file mode 100644 index 0000000..6b3556b --- /dev/null +++ b/include/Void/Time/Clock.hpp @@ -0,0 +1,210 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace Void::Time +{ + +enum class ClockError { + negative_step, + overflow +}; + +/// Injectable monotonic clock interface used by Stopwatch, Async deadlines, and +/// deterministic test harnesses (C-04). +class MonotonicClock +{ +public: + using time_point = std::chrono::steady_clock::time_point; + + [[nodiscard]] virtual time_point now() const noexcept = 0; + virtual ~MonotonicClock() = default; +}; + +/// Injectable civil wall-clock interface for calendar timestamps and scheduling. +class CivilClock +{ +public: + using time_point = std::chrono::system_clock::time_point; + + [[nodiscard]] virtual time_point now() const noexcept = 0; + virtual ~CivilClock() = default; +}; + +class SystemMonotonicClock final : public MonotonicClock +{ +public: + [[nodiscard]] time_point now() const noexcept override + { + return std::chrono::steady_clock::now(); + } + + [[nodiscard]] static const SystemMonotonicClock& instance() noexcept + { + static const SystemMonotonicClock clock; + return clock; + } +}; + +class SystemCivilClock final : public CivilClock +{ +public: + [[nodiscard]] time_point now() const noexcept override + { + return std::chrono::system_clock::now(); + } + + [[nodiscard]] static const SystemCivilClock& instance() noexcept + { + static const SystemCivilClock clock; + return clock; + } +}; + +/// Deterministic, thread-safe manual monotonic clock starting at steady epoch 0. +class ManualClock final : public MonotonicClock +{ +public: + ManualClock() noexcept = default; + + explicit ManualClock(time_point initial) noexcept + : ticks_ns_(std::chrono::duration_cast( + initial.time_since_epoch()) + .count()) + { + } + + [[nodiscard]] time_point now() const noexcept override + { + const auto ns = + std::chrono::nanoseconds{ticks_ns_.load(std::memory_order_acquire)}; + return time_point{ + std::chrono::duration_cast(ns)}; + } + + std::expected + advance(std::chrono::nanoseconds delta) noexcept + { + const std::int64_t step = delta.count(); + if (step < 0) { + return std::unexpected{ClockError::negative_step}; + } + std::int64_t cur = ticks_ns_.load(std::memory_order_relaxed); + for (;;) { + if (step > std::numeric_limits::max() - cur) { + return std::unexpected{ClockError::overflow}; + } + if (ticks_ns_.compare_exchange_weak( + cur, cur + step, std::memory_order_release, + std::memory_order_relaxed)) { + return {}; + } + } + } + + std::expected set(time_point target) noexcept + { + const std::int64_t target_ns = + std::chrono::duration_cast( + target.time_since_epoch()) + .count(); + std::int64_t cur = ticks_ns_.load(std::memory_order_relaxed); + for (;;) { + if (target_ns < cur) { + return std::unexpected{ClockError::negative_step}; + } + if (ticks_ns_.compare_exchange_weak( + cur, target_ns, std::memory_order_release, + std::memory_order_relaxed)) { + return {}; + } + } + } + +private: + std::atomic ticks_ns_{0}; +}; + +/// Deterministic manual civil clock supporting explicit forward/backward jumps +/// for calendar and DST/NTP tests. +class ManualCivilClock final : public CivilClock +{ +public: + ManualCivilClock() noexcept = default; + + explicit ManualCivilClock(time_point initial) noexcept + : ticks_ns_(std::chrono::duration_cast( + initial.time_since_epoch()) + .count()) + { + } + + [[nodiscard]] time_point now() const noexcept override + { + const auto ns = + std::chrono::nanoseconds{ticks_ns_.load(std::memory_order_acquire)}; + return time_point{ + std::chrono::duration_cast(ns)}; + } + + std::expected + advance(std::chrono::nanoseconds delta) noexcept + { + const std::int64_t step = delta.count(); + if (step < 0) { + return std::unexpected{ClockError::negative_step}; + } + std::int64_t cur = ticks_ns_.load(std::memory_order_relaxed); + for (;;) { + if (step > std::numeric_limits::max() - cur) { + return std::unexpected{ClockError::overflow}; + } + if (ticks_ns_.compare_exchange_weak( + cur, cur + step, std::memory_order_release, + std::memory_order_relaxed)) { + return {}; + } + } + } + + void set(time_point target) noexcept + { + const std::int64_t target_ns = + std::chrono::duration_cast( + target.time_since_epoch()) + .count(); + ticks_ns_.store(target_ns, std::memory_order_release); + } + +private: + std::atomic ticks_ns_{0}; +}; + +/// Compute non-negative wait duration until `deadline` in `clock`'s domain. +[[nodiscard]] inline std::chrono::nanoseconds + remaining_until(const MonotonicClock& clock, + MonotonicClock::time_point deadline) noexcept +{ + const std::int64_t now_ns = + std::chrono::duration_cast( + clock.now().time_since_epoch()) + .count(); + const std::int64_t dl_ns = + std::chrono::duration_cast( + deadline.time_since_epoch()) + .count(); + if (dl_ns <= now_ns) { + return std::chrono::nanoseconds{0}; + } + if (now_ns < 0 && + dl_ns > std::numeric_limits::max() + now_ns) { + return std::chrono::nanoseconds::max(); + } + return std::chrono::nanoseconds{dl_ns - now_ns}; +} + +} // namespace Void::Time diff --git a/include/Void/Time/Stopwatch.hpp b/include/Void/Time/Stopwatch.hpp index e157363..f6e5f44 100644 --- a/include/Void/Time/Stopwatch.hpp +++ b/include/Void/Time/Stopwatch.hpp @@ -1,28 +1,22 @@ #pragma once +#include + #include #include +#include #include namespace Void::Time { -/// Wall-clock stopwatch with lap support, built on steady_clock. +enum class StopwatchError { + not_running, + lap_limit_reached +}; + +/// Wall-clock or injected-clock stopwatch with bounded lap history. /// Single-writer; not thread-safe across threads. -/// -/// Explicit style: -/// Stopwatch sw; -/// sw.start(); -/// // ... work ... -/// sw.lap(); -/// sw.stop(); -/// sw.elapsed(); // total elapsed -/// sw.laps(); // lap durations -/// -/// RAII style (auto-started): -/// auto sw = Stopwatch::started(); -/// do_work(); -/// auto ms = sw.elapsed_as(); class Stopwatch { public: @@ -31,9 +25,18 @@ class Stopwatch using TimePoint = Clock::time_point; using Duration = std::chrono::nanoseconds; - /// Constructed stopped with zero elapsed time. + static constexpr std::size_t kDefaultMaxLaps = 4096; + + /// Constructed stopped with zero elapsed time using system monotonic clock. Stopwatch() noexcept = default; + /// Constructed stopped using an injected MonotonicClock (must outlive *this). + explicit Stopwatch(const MonotonicClock& clock, + std::size_t max_laps = kDefaultMaxLaps) noexcept + : clock_(&clock), max_laps_(max_laps) + { + } + /// Convenience factory: a stopwatch already running. [[nodiscard]] static Stopwatch started() noexcept { @@ -42,22 +45,49 @@ class Stopwatch return sw; } - /// Start (or restart) the timer. Clears recorded laps. - void start() noexcept + [[nodiscard]] static Stopwatch + started(const MonotonicClock& clock, + std::size_t max_laps = kDefaultMaxLaps) noexcept { - running_ = true; - start_ = Clock::now(); - laps_.clear(); - last_lap_ = start_; + Stopwatch sw{clock, max_laps}; + sw.start(); + return sw; } - /// Record a lap split without stopping. Returns the lap duration. - Duration lap() + /// Start (or restart) from zero, clearing accumulated time and laps. + void start() noexcept + { + const auto now = clock_->now(); + running_ = true; + accumulated_ = Duration::zero(); + start_ = now; + last_lap_ = now; + laps_.clear(); + } + + /// Resume accumulating from the previous stopped elapsed time without + /// clearing laps. No-op if already running. + void resume() noexcept + { + if (running_) { + return; + } + const auto now = clock_->now(); + running_ = true; + start_ = now; + last_lap_ = now; + } + + /// Record a lap split without stopping (checked against max_laps). + [[nodiscard]] std::expected try_lap() { if (!running_) { - return Duration::zero(); + return std::unexpected{StopwatchError::not_running}; } - const auto now = Clock::now(); + if (laps_.size() >= max_laps_) { + return std::unexpected{StopwatchError::lap_limit_reached}; + } + const auto now = clock_->now(); const auto d = std::chrono::duration_cast(now - last_lap_); laps_.push_back(d); @@ -65,26 +95,34 @@ class Stopwatch return d; } - /// Stop the timer. Returns elapsed time since start. + /// Legacy compatibility lap wrapper; returns zero if stopped or at cap. + Duration lap() + { + auto res = try_lap(); + return res ? *res : Duration::zero(); + } + + /// Stop the timer and freeze accumulated elapsed time. Duration stop() noexcept { if (!running_) { - return elapsed_; + return accumulated_; } - elapsed_ = - std::chrono::duration_cast(Clock::now() - start_); + const auto now = clock_->now(); + accumulated_ += + std::chrono::duration_cast(now - start_); running_ = false; - return elapsed_; + return accumulated_; } - /// Elapsed time (while running: from start to now; stopped: total). + /// Total elapsed time (accumulated + active interval if running). [[nodiscard]] Duration elapsed() const noexcept { if (running_) { - return std::chrono::duration_cast(Clock::now() - - start_); + return accumulated_ + std::chrono::duration_cast( + clock_->now() - start_); } - return elapsed_; + return accumulated_; } /// Elapsed time cast to a specific duration type. @@ -101,16 +139,30 @@ class Stopwatch .count(); } - /// Split: return elapsed and restart in one call. + /// Split: sample the clock once, return elapsed, and restart at the + /// exact same instant. [[nodiscard]] Duration split() noexcept { - const auto d = elapsed(); - start(); - return d; + const auto now = clock_->now(); + const Duration total = + running_ ? accumulated_ + std::chrono::duration_cast( + now - start_) + : accumulated_; + running_ = true; + accumulated_ = Duration::zero(); + start_ = now; + last_lap_ = now; + laps_.clear(); + return total; } [[nodiscard]] bool is_running() const noexcept { return running_; } + [[nodiscard]] std::size_t max_laps() const noexcept + { + return max_laps_; + } + [[nodiscard]] const std::vector& laps() const noexcept { return laps_; @@ -125,15 +177,17 @@ class Stopwatch void reset() noexcept { running_ = false; - elapsed_ = Duration::zero(); + accumulated_ = Duration::zero(); laps_.clear(); } private: + const MonotonicClock* clock_{&SystemMonotonicClock::instance()}; + std::size_t max_laps_{kDefaultMaxLaps}; TimePoint start_{}; TimePoint last_lap_{}; - Duration elapsed_{}; + Duration accumulated_{}; std::vector laps_; bool running_{false}; }; @@ -146,15 +200,20 @@ class ScopedTimer using Clock = Stopwatch::Clock; using Duration = Stopwatch::Duration; - explicit ScopedTimer(Duration& out) - : out_{out}, start_{Clock::now()} + explicit ScopedTimer(Duration& out) noexcept + : out_{out}, clock_{&SystemMonotonicClock::instance()}, + start_{clock_->now()} + { + } + + ScopedTimer(Duration& out, const MonotonicClock& clock) noexcept + : out_{out}, clock_{&clock}, start_{clock_->now()} { } ~ScopedTimer() { - out_ = - std::chrono::duration_cast(Clock::now() - start_); + out_ = std::chrono::duration_cast(clock_->now() - start_); } ScopedTimer(const ScopedTimer&) = delete; @@ -163,6 +222,7 @@ class ScopedTimer private: Duration& out_; + const MonotonicClock* clock_; Clock::time_point start_; }; diff --git a/tests/standalone/Time/Clock.cpp b/tests/standalone/Time/Clock.cpp new file mode 100644 index 0000000..4b4169a --- /dev/null +++ b/tests/standalone/Time/Clock.cpp @@ -0,0 +1,101 @@ +#include +#include +#include +#include + +#include +#include +#include +#include + +using namespace std::chrono_literals; + +Void::Testing::Test manual_clock_starts_at_epoch_and_advances() +{ + Void::Time::ManualClock clock; + Void::Testing::expect_eq(clock.now().time_since_epoch().count(), + std::int64_t{0}); + + const auto adv = clock.advance(25ms); + Void::Testing::expect(adv.has_value()); + Void::Testing::expect_eq(clock.now().time_since_epoch(), 25ms); +} + +Void::Testing::Test manual_clock_rejects_negative_and_overflow() +{ + Void::Time::ManualClock clock{ + Void::Time::MonotonicClock::time_point{100ns}}; + + const auto neg = clock.advance(-1ns); + Void::Testing::expect(!neg.has_value()); + Void::Testing::expect(neg.error() == Void::Time::ClockError::negative_step); + Void::Testing::expect_eq(clock.now().time_since_epoch(), 100ns); + + const auto max_step = std::chrono::nanoseconds{ + std::numeric_limits::max()}; + const auto ovf = clock.advance(max_step); + Void::Testing::expect(!ovf.has_value()); + Void::Testing::expect(ovf.error() == Void::Time::ClockError::overflow); + Void::Testing::expect_eq(clock.now().time_since_epoch(), 100ns); + + const auto back_set = clock.set(Void::Time::MonotonicClock::time_point{50ns}); + Void::Testing::expect(!back_set.has_value()); + Void::Testing::expect(back_set.error() == + Void::Time::ClockError::negative_step); +} + +Void::Testing::Test manual_civil_clock_supports_backward_set() +{ + Void::Time::ManualCivilClock civil{ + Void::Time::CivilClock::time_point{1000s}}; + Void::Testing::expect(civil.advance(5s).has_value()); + Void::Testing::expect_eq( + std::chrono::duration_cast( + civil.now().time_since_epoch()), + 1005s); + + civil.set(Void::Time::CivilClock::time_point{900s}); + Void::Testing::expect_eq( + std::chrono::duration_cast( + civil.now().time_since_epoch()), + 900s); +} + +Void::Testing::Test remaining_until_clamps_expired_deadlines() +{ + Void::Time::ManualClock clock; + const auto deadline = clock.now() + 50ms; + Void::Testing::expect_eq(Void::Time::remaining_until(clock, deadline), + 50ms); + + Void::Testing::expect(clock.advance(80ms).has_value()); + Void::Testing::expect_eq(Void::Time::remaining_until(clock, deadline), 0ns); +} + +Void::Testing::Test manual_clock_concurrent_advances() +{ + Void::Time::ManualClock clock; + std::vector threads; + for (int t = 0; t < 4; ++t) { + threads.emplace_back([&clock]() { + for (int i = 0; i < 1000; ++i) { + (void)clock.advance(1ms); + } + }); + } + for (auto& th : threads) { + th.join(); + } + Void::Testing::expect_eq(clock.now().time_since_epoch(), 4000ms); +} + +Void::Testing::Test scoped_timer_with_manual_clock() +{ + Void::Time::ManualClock clock; + Void::Time::Stopwatch::Duration out{}; + { + Void::Time::ScopedTimer timer{out, clock}; + Void::Testing::expect(clock.advance(42ms).has_value()); + } + Void::Testing::expect_eq(out, 42ms); +} diff --git a/tests/standalone/Time/Stopwatch.cpp b/tests/standalone/Time/Stopwatch.cpp index 66b2dc0..1ba154d 100644 --- a/tests/standalone/Time/Stopwatch.cpp +++ b/tests/standalone/Time/Stopwatch.cpp @@ -137,3 +137,58 @@ Void::Testing::Test scoped_timer_written_on_destruction() (void)d; Void::Testing::expect(true); // ScopedTimer destructor ran without error } + +Void::Testing::Test deterministic_stopwatch_start_stop_resume_split() +{ + using namespace std::chrono_literals; + ManualClock clock; + auto sw = Stopwatch::started(clock); + + Void::Testing::expect(clock.advance(10ms).has_value()); + Void::Testing::expect_eq(sw.elapsed(), 10ms); + + const auto lap1 = sw.try_lap(); + Void::Testing::expect(lap1.has_value() && *lap1 == 10ms); + + const auto stopped = sw.stop(); + Void::Testing::expect_eq(stopped, 10ms); + + // Advancing while stopped must not add to elapsed time. + Void::Testing::expect(clock.advance(100ms).has_value()); + Void::Testing::expect_eq(sw.elapsed(), 10ms); + + sw.resume(); + Void::Testing::expect(clock.advance(5ms).has_value()); + Void::Testing::expect_eq(sw.elapsed(), 15ms); + Void::Testing::expect_eq(sw.lap_count(), std::size_t{1}); + + const auto split_total = sw.split(); + Void::Testing::expect_eq(split_total, 15ms); + Void::Testing::expect_eq(sw.lap_count(), std::size_t{0}); + Void::Testing::expect_eq(sw.elapsed(), Duration::zero()); + + Void::Testing::expect(clock.advance(7ms).has_value()); + Void::Testing::expect_eq(sw.elapsed(), 7ms); +} + +Void::Testing::Test stopwatch_enforces_max_laps_and_not_running() +{ + using namespace std::chrono_literals; + ManualClock clock; + Stopwatch sw{clock, 3}; + + const auto not_running = sw.try_lap(); + Void::Testing::expect(!not_running.has_value()); + Void::Testing::expect(not_running.error() == StopwatchError::not_running); + + sw.start(); + for (int i = 0; i < 3; ++i) { + Void::Testing::expect(clock.advance(1ms).has_value()); + Void::Testing::expect(sw.try_lap().has_value()); + } + Void::Testing::expect(clock.advance(1ms).has_value()); + const auto full = sw.try_lap(); + Void::Testing::expect(!full.has_value()); + Void::Testing::expect(full.error() == StopwatchError::lap_limit_reached); + Void::Testing::expect_eq(sw.lap_count(), std::size_t{3}); +}