A faster way to calculate the day of the week(benjoffe.com)
262 points by gavide 5 days ago | 88 comments
tl;dr: The article presents novel bit-manipulation techniques for computing day-of-week from a day count, outperforming existing solutions (Hinnant, Neri) by 2-3x through exploiting that 7 is a Mersenne number (2³-1), enabling modulus via multiply-add-shift with a rotation constant. Several full-range 32-bit variants are shown, with the fastest achieving just 3 x86 instructions plus a constant load. The techniques generalize to other divisors like x%24 and x%60 via a "power-of-2 padding" formula (n + n/d*k) & mask, which appears novel and is useful for timekeeping code.
HN Discussion:
  • Appreciation for the optimization deep-dive and the technical rabbit hole
  • ~Questions the practical performance need but values the general mod-7 technique
  • ~Notes edge cases like negative day counts requiring fixups not fully addressed
  • Offers alternative mental calculation tricks using Gregorian month/day instead
  • Tangential musings on calendars, time systems, and day-of-week continuity