What a leap second does to Python’s decimal division

This started with an experimental eight-line change to Ruby’s BigDecimal. You can see the reason for all eight in one line of Python.

assert divmod(2 * 10**9, 3) == (666_666_666, 2)

Start with remainder 2. Bring down nine zeros, the size of a block in this Ruby build. You get nine sixes and remainder 2 again. The next division will do exactly the same thing. The patch checks for that equality once, fills the rest of the quotient, and hands the exact remainder back to Ruby’s existing rounding code. Eight-line Ruby change and regression tests

CPython’s Decimal uses a C library called mpdecimal. On our 64-bit build it brings down 19 zeros at a time. Our smallest Python patch handles thirds in eight net lines of C, too. We wanted to know when a shortcut like that mattered in a Python program. The final minute of two consecutive UTC days gave us a way to find out. Python patch 00

The same second on two nights

At 23:59:59 UTC on December 30 and 31, 2016, exactly 86,399 seconds had elapsed since midnight. On the first night the next tick was midnight. On the second it was 23:59:60. NIST’s leap-second record

Our Python program converts each clock label in the last minute to a Julian date in two parts. The first is the date at midnight. The second is Decimal(elapsed_seconds) / Decimal(seconds_in_day), following the convention the IAU’s SOFA library uses for UTC. So the same clock reading gives 86399 / 86400 on Friday and 86399 / 86401 on Saturday. We asked for 1,000 decimal places to give long division some work. A clock that ticks once a second needs far fewer. SOFA time-scale cookbook, footnote 9 · Python converter

Watch the remainders for the first five blocks. The quotient from each divmod supplies 19 digits. Its remainder determines what happens next.

B = 10**19

def remainders(elapsed, day_length):
    r = elapsed
    for _ in range(5):
        _, r = divmod(r * B, day_length)
        yield r

for day in (86_400, 86_401):
    print(day, list(remainders(86_399, day)))
86400 [22400, 51200, 80000, 22400, 51200]
86401 [21477, 16705, 25034, 52303, 80336]

On Friday, 22,400 comes back three blocks later. You can see the repetition in the fraction itself, 0.999988425925925…. Once the remainder returns, the next 57 digits are a copy of the previous 57.

There’s a small Python patch for the Ruby idea, too. With a one-block divisor, two different remainders always produce different next blocks when you bring down zeros. So two equal blocks in a row prove that you can keep copying. The compact version of patch 01 handles 1/6 in 16 net lines of C. Another nine lines recognize complementary blocks, as in 1/11. Both compact patches and their timings

Patch 03 looks up to four blocks ahead. Across Friday’s final minute, 40 fractions repeated after three blocks, 18 settled into a single repeating block, and two terminated. The patch could finish all 60 by copying. Patch 03 · Measured paths

On Saturday, 21,477 takes 12,342 blocks to come back. The divisor 86,401 leaves one when divided by four, which looks promising. For this fraction to repeat after four blocks, though, pow(B, 4, 86_401) would have to give one. It gives 17,049. We only asked for about 53 blocks of output. Every one of Saturday’s 61 divisions missed the four-block check.

Starting long division in the middle

A long cycle still lets us calculate where we’ll be eleven blocks from now. One step takes remainder r to r * B % d, where d is the divisor. Eleven steps multiply by B**11 modulo d. Here are four starting remainders, eleven blocks apart, for Saturday’s division.

r, d = 21_477, 86_401
print([r * pow(B, offset, d) % d for offset in (0, 11, 22, 33)])
# [21477, 70467, 38707, 84517]

Patch 04 uses this to split the remaining digits into four runs after 03’s check misses. It calculates the starting remainder for each run and interleaves them on one CPU core. The processor can work on one run while another waits for its remainder. The patch also precomputes a reciprocal so each step can use multiplication. On this build it takes that route when the divisor fits in 32 bits and at least 32 blocks of zero padding remain. Patch 04 · Separate timings for the two changes

What the two minutes cost

We timed the whole minute, including parsing each clock label and formatting both date parts in memory. Each cell gives the median time from each of two passes at 1,000 digits. We used the same CPython 3.14.6 executable on one arm64 Mac and changed the mpdecimal 4.0.1 library it loaded.

UTC minute Stock Patch 03 Patch 04
Dec 30 · 60 timestamps 157 / 161 µs 130 / 128 µs 127 / 132 µs
Dec 31 · 61 timestamps 164 / 161 µs 164 / 164 µs 135 / 136 µs

In paired runs, 03 was 1.24–1.26× as fast as stock on Friday. On Saturday it was within 1% of stock, and 04 was 1.21× as fast as 03 in both passes. At Python’s default 28-digit precision, all three builds took about 49–50 µs per minute. Paired measurements and controls · Timing data

One experiment explains why the miss mattered. An exact test predicted all 61 misses in advance. It skipped 244 search steps and saved zero divisions. Each step of the old search had already written 19 digits that Python still needed. Patch 04 sped up the leap minute by changing how it computed those remaining digits. Counts from both implementations

The smallest follow-up changed one condition. Patch 05 let the four runs start with four blocks left, down from 32. In a Python series calculation that repeatedly evaluates Decimal(1) / (k*k), most divisions at 384 decimal places landed between those cutoffs. That single edit made the whole calculation 1.25–1.27× as fast as 04. At 128 places a miss left just two blocks. Patch 06 made the search itself cheaper for small divisors and brought that shorter calculation within 1% of ordinary half-word division. The one-line change · Patch 05 measurements · Patch 06 measurements

Try both minutes

Download the Python example, patches and timings (ZIP)

The remainder examples above run in plain Python. To time the complete conversions, run the following from the directory containing the timing script.

python3 time_utc_minutes.py

The script checks every output row against integer arithmetic and times your installed Python at 28 and 1,000 digits. For a patch-to-patch comparison, the build recipe runs one dynamically linked Python against stock, 03 and 04 and verifies which library each process actually loads. Quick timing script · Build and benchmark instructions