AK: Add Time::now_<clock_id> 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.
This commit is contained in:
Brian Gianforcaro 2021-08-14 14:40:38 -07:00 committed by Andreas Kling
parent 188e5f018f
commit dae17ce7e3
Notes: sideshowbarker 2024-07-18 05:41:17 +09:00
2 changed files with 39 additions and 0 deletions

View file

@ -14,6 +14,7 @@
# include <Kernel/UnixTypes.h> # include <Kernel/UnixTypes.h>
#else #else
# include <sys/time.h> # include <sys/time.h>
# include <time.h>
#endif #endif
namespace AK { namespace AK {
@ -288,4 +289,35 @@ Time Time::from_half_sanitized(i64 seconds, i32 extra_seconds, u32 nanoseconds)
return Time { seconds + extra_seconds, 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
} }

View file

@ -143,6 +143,13 @@ public:
constexpr static Time zero() { return Time(0, 0); }; constexpr static Time zero() { return Time(0, 0); };
constexpr static Time max() { return Time(0x7fff'ffff'ffff'ffffLL, 999'999'999); }; 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). // Truncates towards zero (2.8s to 2s, -2.8s to -2s).
i64 to_truncated_seconds() const; i64 to_truncated_seconds() const;
i64 to_truncated_milliseconds() const; i64 to_truncated_milliseconds() const;