[libc-commits] [libc] [libc] Implement fast date conversion algorithm of Ben Joffe (PR #208312)

Michael Jones via libc-commits libc-commits at lists.llvm.org
Thu Jul 9 10:53:16 PDT 2026


================
@@ -122,14 +122,17 @@ LIBC_INLINE ErrorOr<tm *> localtime(const time_t *t_ptr) {
   return time_utils::localtime_internal(t_ptr, &result);
 }
 
-// Returns number of years from (1, year).
-LIBC_INLINE constexpr int64_t get_num_of_leap_years_before(int64_t year) {
-  return (year / 4) - (year / 100) + (year / 400);
-}
-
 // Returns True if year is a leap year.
+// Uses the Drepper-Neri-Schneider algorithm (version 3).
+// https://www.benjoffe.com/fast-leap-year#drepper-neri-schneider
+//
+// % 25 is faster than % 100 on modern compilers. False positives (years
+// divisible by 25 but not 100) are harmless: the & 15 check only differs
+// from & 3 when the year truly is a century year, and non-century years
+// that happen to be divisible by 25 always pass both checks identically.
----------------
michaelrj-google wrote:

nit: this optimization seems reasonable, but you should probably name the variable something other than `is_cen` since it's not actually checking for centuries.

https://github.com/llvm/llvm-project/pull/208312


More information about the libc-commits mailing list