From dae17ce7e3b6a48d2e100757ebf25dd5bc431f03 Mon Sep 17 00:00:00 2001 From: Brian Gianforcaro Date: Sat, 14 Aug 2021 14:40:38 -0700 Subject: [PATCH] AK: Add Time::now_ functions for obtaining the current time In the quest of removing as timespec / timeval usage in the Userland as possible, we need a way to conveniently retrieving the current clock time from the kernel and storing it in `AK::Time` format. --- AK/Time.cpp | 32 ++++++++++++++++++++++++++++++++ AK/Time.h | 7 +++++++ 2 files changed, 39 insertions(+) diff --git a/AK/Time.cpp b/AK/Time.cpp index 170446b0a36..b7740371b67 100644 --- a/AK/Time.cpp +++ b/AK/Time.cpp @@ -14,6 +14,7 @@ # include #else # include +# include #endif namespace AK { @@ -288,4 +289,35 @@ Time Time::from_half_sanitized(i64 seconds, i32 extra_seconds, u32 nanoseconds) return Time { seconds + extra_seconds, nanoseconds }; } +#ifndef KERNEL +namespace { +static Time now_time_from_clock(clockid_t clock_id) +{ + timespec now_spec {}; + ::clock_gettime(clock_id, &now_spec); + return Time::from_timespec(now_spec); +} +} +Time Time::now_realtime() +{ + return now_time_from_clock(CLOCK_REALTIME); +} + +Time Time::now_realtime_coarse() +{ + return now_time_from_clock(CLOCK_REALTIME_COARSE); +} + +Time Time::now_monotonic() +{ + return now_time_from_clock(CLOCK_MONOTONIC); +} + +Time Time::now_monotonic_coarse() +{ + return now_time_from_clock(CLOCK_MONOTONIC_COARSE); +} + +#endif + } diff --git a/AK/Time.h b/AK/Time.h index 8a754ab0ff7..585f676af53 100644 --- a/AK/Time.h +++ b/AK/Time.h @@ -143,6 +143,13 @@ public: constexpr static Time zero() { return Time(0, 0); }; constexpr static Time max() { return Time(0x7fff'ffff'ffff'ffffLL, 999'999'999); }; +#ifndef KERNEL + [[nodiscard]] static Time now_realtime(); + [[nodiscard]] static Time now_realtime_coarse(); + [[nodiscard]] static Time now_monotonic(); + [[nodiscard]] static Time now_monotonic_coarse(); +#endif + // Truncates towards zero (2.8s to 2s, -2.8s to -2s). i64 to_truncated_seconds() const; i64 to_truncated_milliseconds() const;