[libc-commits] [libc] [libc] Use fast day-of-week and time-of-day algorithms in time_utils (PR #238163)
via libc-commits
libc-commits at lists.llvm.org
Mon Nov 9 11:51:53 PST 2026
================
@@ -110,6 +110,76 @@ LIBC_INLINE constexpr int get_days_in_year(const int year) {
: time_constants::DAYS_PER_NON_LEAP_YEAR;
}
+// Returns the day of the week [0=Sun, 1=Mon, ..., 6=Sat] for a count of days
+// since the Unix epoch (1970-01-01, a Thursday), i.e. (unix_days + 4) mod 7
+// with a non-negative result.
+//
+// Uses Ben Joffe's "Unreasonably Fast Mul-Add-Shift" algorithm (Article 5).
+// https://www.benjoffe.com/fast-day-of-week
+//
+// Since 7 = 2^3 - 1 is a Mersenne number, x mod 7 == floor(x * 8 / 7) mod 8.
+// Multiplying by M = ceil(2^64 / 7) and keeping the low 64 bits places
+// floor(x * 8 / 7) mod 8 in the top 3 bits; the final mod 8 is free. Adding Z
+// before the shift rotates the result so that day 0 maps to Thursday (4).
+//
+// Valid for unix_days in [-230471710930685136, 230696890912053658], which is
+// about +/-631 trillion years and far exceeds the range accepted by
+// update_from_seconds (about +/-7.9e11 days).
+LIBC_INLINE constexpr int get_weekday(const int64_t unix_days) {
+ // M = ceil(2^64 / 7).
+ constexpr uint64_t M = UINT64_MAX / 7 + 1;
----------------
rtenneti-google wrote:
Done.
https://github.com/llvm/llvm-project/pull/238163
More information about the libc-commits
mailing list