[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:31 PST 2026


https://github.com/rtenneti-google updated https://github.com/llvm/llvm-project/pull/238163

>From c4c6425a95d9f3445a2768929d588e179d930e19 Mon Sep 17 00:00:00 2001
From: Raman Tenneti <rtenneti at google.com>
Date: Mon, 2 Nov 2026 11:28:52 -0800
Subject: [PATCH] [libc] Use fast day-of-week and time-of-day algorithms in
 time_utils

Add two constexpr helpers to time_utils.h and use them in
update_from_seconds:

- get_weekday(unix_days): Ben Joffe's mul-add-shift weekday algorithm
  (https://www.benjoffe.com/fast-day-of-week). Because 7 = 2^3 - 1,
  x mod 7 == floor(x * 8 / 7) mod 8. Multiplying by ceil(2^64 / 7) and
  adding a rotation constant puts the weekday in the top 3 bits. It is
  valid for about +/-631 trillion years, well beyond the range accepted
  by update_from_seconds.
- get_time_of_day(seconds_of_day): Ben Joffe's "V2 - Fixed-Point Hi/Low
  Bits" algorithm (https://www.benjoffe.com/fast-time-of-day). It splits
  seconds into hour, minute and second with four multiplications and no
  division. Hour and minute come from the high and low bits of one
  product and the second comes from a separate product, so the two run
  in parallel instead of the hour -> remainder -> minute -> second chain.
  It is valid for [0, 2255818].

Add time_utils_test.cpp, which compares both helpers against plain
modulo/division:
- known dates/times and static_assert checks that both helpers are
  constexpr
- every input of get_time_of_day up to 2255818 seconds
- every day within +/-10 million days of the epoch
- one million days at each end of the supported and documented ranges
- a sparse sweep (step coprime with 7) across the whole documented
  get_weekday range
- update_from_seconds over +/-10 years and near +/-2.1 billion years

On an Intel Xeon @ 2.60GHz at -O2, update_from_seconds is 9-14% faster
with clang 21 and 4-5% faster with GCC 15. On their own, the weekday
code is 2.2-2.8x faster and the time-of-day code is 1.3-1.6x faster.
---
 libc/src/time/time_utils.cpp           |  19 +--
 libc/src/time/time_utils.h             |  75 ++++++++++
 libc/test/src/time/CMakeLists.txt      |  21 +++
 libc/test/src/time/time_utils_test.cpp | 197 +++++++++++++++++++++++++
 4 files changed, 300 insertions(+), 12 deletions(-)
 create mode 100644 libc/test/src/time/time_utils_test.cpp

diff --git a/libc/src/time/time_utils.cpp b/libc/src/time/time_utils.cpp
index beb6d3d2130bcd..771a4c8dd63a93 100644
--- a/libc/src/time/time_utils.cpp
+++ b/libc/src/time/time_utils.cpp
@@ -184,10 +184,7 @@ ErrorOr<void> update_from_seconds(time_t total_seconds, tm *tm) {
     yday++;
 
   // Step 5: Calculate day of week [0=Sun, 1=Mon, ..., 6=Sat]
-  // Unix epoch 1970-01-01 was Thursday (4)
-  int wday = static_cast<int>((unix_days + 4) % 7);
-  if (wday < 0)
-    wday += 7;
+  int wday = get_weekday(unix_days);
 
   // Step 6: Populate tm structure with all calculated values
   tm->tm_year = year - time_constants::TIME_YEAR_BASE; // Years since 1900
@@ -196,14 +193,12 @@ ErrorOr<void> update_from_seconds(time_t total_seconds, tm *tm) {
   tm->tm_wday = wday;                                  // Day of week [0, 6]
   tm->tm_yday = yday;                                  // Day of year [0, 365]
 
-  // Calculate time components from remaining seconds
-  tm->tm_hour =
-      static_cast<int>(remaining_seconds / time_constants::SECONDS_PER_HOUR);
-  tm->tm_min =
-      static_cast<int>(remaining_seconds / time_constants::SECONDS_PER_MIN %
-                       time_constants::SECONDS_PER_MIN);
-  tm->tm_sec =
-      static_cast<int>(remaining_seconds % time_constants::SECONDS_PER_MIN);
+  // Calculate time components from remaining seconds [0, 86399]
+  TimeOfDay time_of_day =
+      get_time_of_day(static_cast<uint32_t>(remaining_seconds));
+  tm->tm_hour = time_of_day.hour;
+  tm->tm_min = time_of_day.minute;
+  tm->tm_sec = time_of_day.second;
   tm->tm_isdst = 0; // Daylight saving time flag (not implemented)
 
   return {};
diff --git a/libc/src/time/time_utils.h b/libc/src/time/time_utils.h
index 8448ba31b04103..a2ab1f0c39cfa5 100644
--- a/libc/src/time/time_utils.h
+++ b/libc/src/time/time_utils.h
@@ -110,6 +110,81 @@ 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 / time_constants::DAYS_PER_WEEK) + 1;
+  // Z rotates the result so that day 0 maps to Thursday: its top 3 bits
+  // (0x9492 >> 13 == 4) encode Thursday, and the remaining low bits are a
+  // rounding bias (from Joffe's article) that positions the window of exact
+  // results to give the valid range documented above.
+  constexpr uint64_t Z = 0x9492ULL << 48;
+  return static_cast<int>((static_cast<uint64_t>(unix_days) * M + Z) >> 61);
+}
+
+// Hour, minute and second within a day.
+struct TimeOfDay {
+  // Hour of the day [0, 23].
+  int hour;
+  // Minute of the hour [0, 59].
+  int minute;
+  // Second of the minute [0, 59].
+  int second;
+};
+
+// Splits the number of seconds elapsed within a day [0, 86399] into hours,
+// minutes and seconds.
+//
+// Uses Ben Joffe's "V2 - Fixed-Point Hi/Low Bits" algorithm (Article 6).
+// https://www.benjoffe.com/fast-time-of-day
+//
+// Instead of the sequential chain hour -> remainder -> minute -> second, both
+// fixed-point products are computed directly from seconds_of_day so they can
+// run in parallel:
+//   - The high 32 bits of seconds_of_day * ceil(2^32 / 3600) are the hour,
+//     and the low 32 bits are the fraction of the current hour elapsed;
+//     scaling that fraction by 60 yields the minute.
+//   - The low 32 bits of seconds_of_day * ceil(2^32 / 60) are the fraction of
+//     the current minute elapsed; scaling it by 60 yields the second.
+//
+// This compiles to four multiplications (two pairs that can overlap) and no
+// division.
+// Valid for seconds_of_day in [0, 2255818] (up to 626:36:58), which covers a
+// full day with a wide margin.
+LIBC_INLINE constexpr TimeOfDay get_time_of_day(const uint32_t seconds_of_day) {
+  // H_MUL = ceil(2^32 / 3600) = 1193047.
+  constexpr uint64_t H_MUL =
+      ((1ULL << 32) / time_constants::SECONDS_PER_HOUR) + 1;
+  // M_MUL = ceil(2^32 / 60) = 71582789.
+  constexpr uint64_t M_MUL =
+      ((1ULL << 32) / time_constants::SECONDS_PER_MIN) + 1;
+  const uint64_t HOUR_PRODUCT = static_cast<uint64_t>(seconds_of_day) * H_MUL;
+  const uint32_t MINUTE_FRACTION = static_cast<uint32_t>(HOUR_PRODUCT);
+  const uint32_t SECOND_FRACTION =
+      static_cast<uint32_t>(seconds_of_day * M_MUL);
+  return {static_cast<int>(HOUR_PRODUCT >> 32),
+          static_cast<int>((static_cast<uint64_t>(MINUTE_FRACTION) *
+                            time_constants::MINUTES_PER_HOUR) >>
+                           32),
+          static_cast<int>((static_cast<uint64_t>(SECOND_FRACTION) *
+                            time_constants::SECONDS_PER_MIN) >>
+                           32)};
+}
+
 // This is a helper class that takes a struct tm and lets you inspect its
 // values. Where relevant, results are bounds checked and returned as optionals.
 /// Class to read fields from tm structure.
diff --git a/libc/test/src/time/CMakeLists.txt b/libc/test/src/time/CMakeLists.txt
index 037394f8741775..39aeb0735e630e 100644
--- a/libc/test/src/time/CMakeLists.txt
+++ b/libc/test/src/time/CMakeLists.txt
@@ -326,3 +326,24 @@ add_libc_test(
     libc.src.time.tz_variables
     libc.src.time.tzset
 )
+
+# Depending on the gmtime entrypoint skips this test on targets that don't
+# enable the time functions. time_utils requires a 64-bit time_t and does not
+# compile on overlay builds whose system time_t is 32-bit (e.g. armhf).
+add_libc_test(
+  time_utils_test
+  SUITE
+    libc-time-tests
+  SRCS
+    time_utils_test.cpp
+  CXX_STANDARD
+    20
+  DEPENDS
+    libc.hdr.limits_macros
+    libc.hdr.stdint_proxy
+    libc.hdr.types.struct_tm
+    libc.hdr.types.time_t
+    libc.src.time.gmtime
+    libc.src.time.time_constants
+    libc.src.time.time_utils
+)
diff --git a/libc/test/src/time/time_utils_test.cpp b/libc/test/src/time/time_utils_test.cpp
new file mode 100644
index 00000000000000..ca4a6a0b11492b
--- /dev/null
+++ b/libc/test/src/time/time_utils_test.cpp
@@ -0,0 +1,197 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Unit tests for the time_utils helpers get_weekday, get_time_of_day and
+/// update_from_seconds.
+///
+//===----------------------------------------------------------------------===//
+
+#include "hdr/limits_macros.h"
+#include "hdr/stdint_proxy.h"
+#include "hdr/types/struct_tm.h"
+#include "hdr/types/time_t.h"
+#include "src/time/time_constants.h"
+#include "src/time/time_utils.h"
+#include "test/UnitTest/Test.h"
+
+namespace time_constants = LIBC_NAMESPACE::time_constants;
+namespace time_utils = LIBC_NAMESPACE::time_utils;
+
+// Straightforward reference: (unix_days + 4) mod 7 with a non-negative result.
+static int reference_weekday(int64_t unix_days) {
+  int64_t wday = (unix_days % 7 + 7 + 4) % 7;
+  return static_cast<int>(wday);
+}
+
+// Smallest and largest day counts accepted by update_from_seconds.
+constexpr int64_t MIN_SUPPORTED_DAYS =
+    INT_MIN *
+    static_cast<int64_t>(time_constants::NUMBER_OF_SECONDS_IN_LEAP_YEAR) /
+    time_constants::SECONDS_PER_DAY;
+constexpr int64_t MAX_SUPPORTED_DAYS =
+    INT_MAX *
+    static_cast<int64_t>(time_constants::NUMBER_OF_SECONDS_IN_LEAP_YEAR) /
+    time_constants::SECONDS_PER_DAY;
+
+// Documented valid input range of get_weekday.
+constexpr int64_t MIN_WEEKDAY_DAYS = -230471710930685136LL;
+constexpr int64_t MAX_WEEKDAY_DAYS = 230696890912053658LL;
+
+// Documented valid input range of get_time_of_day.
+constexpr uint32_t MAX_TIME_OF_DAY_SECONDS = 2255818;
+
+TEST(LlvmLibcTimeUtilsGetWeekday, KnownDates) {
+  // 1970-01-01 Thursday
+  EXPECT_EQ(time_utils::get_weekday(0), 4);
+  // 1969-12-31 Wednesday
+  EXPECT_EQ(time_utils::get_weekday(-1), 3);
+  // 1970-01-02 Friday
+  EXPECT_EQ(time_utils::get_weekday(1), 5);
+  // 1970-01-04 Sunday
+  EXPECT_EQ(time_utils::get_weekday(3), 0);
+  // 1900-01-01 Monday
+  EXPECT_EQ(time_utils::get_weekday(-25567), 1);
+  // 2000-01-01 Saturday
+  EXPECT_EQ(time_utils::get_weekday(10957), 6);
+  // 2038-01-19 Tuesday
+  EXPECT_EQ(time_utils::get_weekday(24855), 2);
+}
+
+TEST(LlvmLibcTimeUtilsGetWeekday, IsConstexpr) {
+  static_assert(time_utils::get_weekday(0) == 4);
+  static_assert(time_utils::get_weekday(-1) == 3);
+  static_assert(time_utils::get_weekday(10957) == 6);
+}
+
+TEST(LlvmLibcTimeUtilsGetWeekday, MatchesReferenceAroundEpoch) {
+  // About +/-27,000 years around the Unix epoch.
+  for (int64_t days = -10'000'000; days <= 10'000'000; ++days)
+    ASSERT_EQ(time_utils::get_weekday(days), reference_weekday(days));
+}
+
+TEST(LlvmLibcTimeUtilsGetWeekday, MatchesReferenceAtSupportedLimits) {
+  // Every day near both ends of the range accepted by update_from_seconds.
+  for (int64_t i = 0; i < 1'000'000; ++i) {
+    ASSERT_EQ(time_utils::get_weekday(MIN_SUPPORTED_DAYS + i),
+              reference_weekday(MIN_SUPPORTED_DAYS + i));
+    ASSERT_EQ(time_utils::get_weekday(MAX_SUPPORTED_DAYS - i),
+              reference_weekday(MAX_SUPPORTED_DAYS - i));
+  }
+}
+
+TEST(LlvmLibcTimeUtilsGetWeekday, MatchesReferenceAtDocumentedLimits) {
+  for (int64_t i = 0; i < 1'000'000; ++i) {
+    ASSERT_EQ(time_utils::get_weekday(MIN_WEEKDAY_DAYS + i),
+              reference_weekday(MIN_WEEKDAY_DAYS + i));
+    ASSERT_EQ(time_utils::get_weekday(MAX_WEEKDAY_DAYS - i),
+              reference_weekday(MAX_WEEKDAY_DAYS - i));
+  }
+}
+
+TEST(LlvmLibcTimeUtilsGetWeekday, MatchesReferenceAcrossRange) {
+  // Sparse sweep across the whole documented range using a step that is
+  // coprime with 7 so all residues are exercised.
+  constexpr int64_t STEP = 1'000'000'007LL * 1009;
+  for (int64_t days = MIN_WEEKDAY_DAYS; days <= MAX_WEEKDAY_DAYS - STEP;
+       days += STEP)
+    ASSERT_EQ(time_utils::get_weekday(days), reference_weekday(days));
+}
+
+TEST(LlvmLibcTimeUtilsGetTimeOfDay, KnownTimes) {
+  time_utils::TimeOfDay t = time_utils::get_time_of_day(0);
+  EXPECT_EQ(t.hour, 0);
+  EXPECT_EQ(t.minute, 0);
+  EXPECT_EQ(t.second, 0);
+
+  t = time_utils::get_time_of_day(59);
+  EXPECT_EQ(t.hour, 0);
+  EXPECT_EQ(t.minute, 0);
+  EXPECT_EQ(t.second, 59);
+
+  t = time_utils::get_time_of_day(60);
+  EXPECT_EQ(t.hour, 0);
+  EXPECT_EQ(t.minute, 1);
+  EXPECT_EQ(t.second, 0);
+
+  t = time_utils::get_time_of_day(3599);
+  EXPECT_EQ(t.hour, 0);
+  EXPECT_EQ(t.minute, 59);
+  EXPECT_EQ(t.second, 59);
+
+  t = time_utils::get_time_of_day(3600);
+  EXPECT_EQ(t.hour, 1);
+  EXPECT_EQ(t.minute, 0);
+  EXPECT_EQ(t.second, 0);
+
+  // 12:34:56
+  t = time_utils::get_time_of_day(12 * 3600 + 34 * 60 + 56);
+  EXPECT_EQ(t.hour, 12);
+  EXPECT_EQ(t.minute, 34);
+  EXPECT_EQ(t.second, 56);
+
+  // Last second of the day: 23:59:59
+  t = time_utils::get_time_of_day(86399);
+  EXPECT_EQ(t.hour, 23);
+  EXPECT_EQ(t.minute, 59);
+  EXPECT_EQ(t.second, 59);
+}
+
+TEST(LlvmLibcTimeUtilsGetTimeOfDay, IsConstexpr) {
+  constexpr time_utils::TimeOfDay TIME_OF_DAY =
+      time_utils::get_time_of_day(86399);
+  static_assert(TIME_OF_DAY.hour == 23 && TIME_OF_DAY.minute == 59 &&
+                TIME_OF_DAY.second == 59);
+}
+
+TEST(LlvmLibcTimeUtilsGetTimeOfDay, ExhaustiveDocumentedRange) {
+  for (uint32_t s = 0; s <= MAX_TIME_OF_DAY_SECONDS; ++s) {
+    time_utils::TimeOfDay t = time_utils::get_time_of_day(s);
+    ASSERT_EQ(t.hour, static_cast<int>(s / 3600));
+    ASSERT_EQ(t.minute, static_cast<int>(s / 60 % 60));
+    ASSERT_EQ(t.second, static_cast<int>(s % 60));
+  }
+}
+
+// Checks the weekday and time of day that update_from_seconds produces for
+// seconds against straightforward arithmetic.
+static void expect_weekday_and_time_of_day(time_t seconds) {
+  tm result{};
+  ASSERT_TRUE(time_utils::update_from_seconds(seconds, &result).has_value());
+  time_t days = seconds / time_constants::SECONDS_PER_DAY;
+  time_t rem = seconds % time_constants::SECONDS_PER_DAY;
+  if (rem < 0) {
+    rem += time_constants::SECONDS_PER_DAY;
+    --days;
+  }
+  EXPECT_EQ(result.tm_wday, reference_weekday(days));
+  EXPECT_EQ(result.tm_hour, static_cast<int>(rem / 3600));
+  EXPECT_EQ(result.tm_min, static_cast<int>(rem / 60 % 60));
+  EXPECT_EQ(result.tm_sec, static_cast<int>(rem % 60));
+}
+
+TEST(LlvmLibcTimeUtilsUpdateFromSeconds, WeekdayAndTimeOfDay) {
+  // Step by 3599 seconds (one second short of an hour) over several years on
+  // both sides of the epoch, so each successive hour is sampled at a different
+  // second offset, comparing with straightforward arithmetic.
+  constexpr time_t SPAN = 10LL * 366 * time_constants::SECONDS_PER_DAY;
+  for (time_t seconds = -SPAN; seconds <= SPAN; seconds += 3599)
+    expect_weekday_and_time_of_day(seconds);
+}
+
+TEST(LlvmLibcTimeUtilsUpdateFromSeconds, FarFutureAndPast) {
+  // About +/-2.1 billion years, close to the largest years that fit in an int.
+  constexpr time_t FAR_SECONDS =
+      INT_MAX * static_cast<int64_t>(time_constants::DAYS_PER_NON_LEAP_YEAR) *
+      time_constants::SECONDS_PER_DAY;
+  for (time_t offset = 0; offset < 2 * time_constants::SECONDS_PER_DAY;
+       offset += 1234) {
+    expect_weekday_and_time_of_day(FAR_SECONDS - offset);
+    expect_weekday_and_time_of_day(-FAR_SECONDS + offset);
+  }
+}



More information about the libc-commits mailing list