Back to Devoured - August 20, 2026
DEVOURED
A faster way to calculate the day of the week

A faster way to calculate the day of the week

Tech Ben Joffe
A new class of 'unreasonably fast' algorithms can calculate the day of the week with minimal CPU latency by utilizing bitwise manipulation and custom magic multipliers.
What: Developer Ben Joffe introduces techniques to compute weekdays using single multiplications and bit-shifts, outperforming standard modulo operations. These methods target high-performance database engines and date libraries, using Mersenne number properties to achieve throughput and latency improvements on x86 and ARM architectures.
Why it matters: This research demonstrates how deep optimization of fundamental calendar math can yield massive speed gains for data-intensive applications.
Takeaway: For high-performance date libraries, benchmark your current weekday calculation against the V1-V3 algorithms provided in the Joffe repository.
Deep dive
  • Calculating weekdays via (rd + 4) % 7 is standard but relatively slow on modern CPUs.
  • Standard compiler output for division is often inefficient because 7 is an uncooperative divisor.
  • Mersenne number properties (2^N - 1) allow for fast modulus operations via custom magic multipliers and right-shifts.
  • The 'Unreasonably Fast' algorithms leverage superscalar CPU execution to perform multiplication and shifts in parallel.
  • Variant 2 achieves high throughput by replacing correction terms with two parallel multiplications.
  • Variant 3, the fastest, uses a single LEA instruction to combine low/high bits from a multiplication.
Decoder
  • Rata-die: A day-count system where dates are represented as integer offsets from an epoch (e.g., 0001-01-01).
  • Superscalar: A CPU architecture that allows for the execution of more than one instruction per clock cycle by dispatching multiple operations to different execution units.
  • LEA: Load Effective Address; an x86 instruction that can perform complex arithmetic (addition/multiplication by small constants) in a single cycle.
Original article

Full article content is not available for inline reading.

Read the original article →

Explore all 57 articles in today's digest

Fresh dev news, AI-digested daily. Never miss a trend at devoured.fyi