Skip to content

Divide wide integers limb by limb instead of bit by bit - #112477

Merged
thevar1able merged 8 commits into
masterfrom
faster-wide-integer-division
Aug 7, 2026
Merged

thevar1able merged 8 commits into
masterfrom
faster-wide-integer-division

Conversation

@thevar1able

Copy link
Copy Markdown
Member

Related: #112457

_impl::divide in base/base/wide_integer_impl.h used shift-and-subtract restoring long division for anything wider than 128 bits: one quotient bit per iteration, up to 256 of them, each a full 256-bit compare, subtract, OR and two shifts. It now dispatches on the size of the divisor instead — a loop of 128 / 64 divisions when the divisor fits in a single 64-bit limb, Knuth's Algorithm D otherwise — so a quotient limb is produced per iteration rather than a bit. The 128-bit hardware fast path is untouched.

operator_slash and operator_percent no longer route 256-bit operands through _BitInt(256). Addition, subtraction and multiplication keep doing so, but for division the compiler emits a generic bignum sequence that is far slower than the above: about 287 ns against 12 ns for a 256-bit value divided by 10^18. That also restores constexpr division for Int256 and UInt256, which _BitInt(256) had taken away because the conversion goes through a reinterpret_cast.

_BitInt(256) was only used on x86-64, so until now division ran different code there than on every other platform. Both now share one path.

Results

intDiv over 2 million UInt256 values, single thread, AMD Zen 5:

query before after
intDiv(u, 997) 1540 ms 107 ms 14.4x
intDiv(u, 10^18) 1243 ms 108 ms 11.5x
modulo(u, 10^18) 1145 ms 106 ms 10.8x
intDiv(u, 10^20) 1209 ms 136 ms 8.9x
intDiv(i, 10^18), signed 1126 ms 151 ms 7.5x
intDiv(u, 10^40) 814 ms 132 ms 6.2x
intDiv(u, 10^76) 118 ms 114 ms 1.0x
intDiv(u, v), both full width 158 ms 157 ms 1.0x

Decimal256 formatting divides by the scale multiplier, so it benefits too: toString of a Decimal256(76) is 6.1x faster and of a Decimal256(40) 3.4x.

The last two rows are the cases the old algorithm was already good at — when the divisor is nearly as large as the dividend the quotient has few significant bits, so its loop exited almost immediately. toString of a UInt256 and intDiv of a UInt128 are unchanged for the same reason. Timings are identical from -march=x86-64 through -march=x86-64-v4, with bit-identical results; there is no SIMD and no runtime dispatch.

There was no division test coverage to speak of, so this adds three tests. DivisionKnownValues pins values computed independently, DivisionInvariants checks q * b + r == a and the sign and magnitude of the remainder over random operands of random bit widths, and DivisionEdgeCases runs every power of two and its neighbours, and every power of ten, against each other in both roles — covering dividends shorter than the divisor, single-limb divisors, and every normalization shift. New perf test wide_integer_division.xml. During development the new code was also differentially tested against the algorithm it replaces over 5.2 million unsigned and 0.9 million signed divisions at 128, 256 and 512 bits.

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Division of 256-bit integers (Int256, UInt256, and Decimal256) now computes the quotient one 64-bit limb at a time, using a loop of 128 / 64 divisions when the divisor fits in 64 bits and Knuth's Algorithm D otherwise, instead of one bit at a time with shift-and-subtract long division. This affects intDiv, modulo, Decimal256 arithmetic and conversion of these types to text.

`_impl::divide` in `base/base/wide_integer_impl.h` used shift-and-subtract
restoring long division for anything wider than 128 bits: one quotient bit per
iteration, up to 256 of them, each a full 256-bit compare, subtract, OR and two
shifts. It now dispatches on the size of the divisor instead - a loop of 128 / 64
divisions when the divisor fits in a single 64-bit limb, and Knuth's Algorithm D
otherwise - so a quotient *limb* is produced per iteration rather than a bit.
Both are portable, and both stay usable in constant evaluation, which the
128-bit fast path already relied on.

`operator_slash` and `operator_percent` no longer route 256-bit operands through
`_BitInt(256)`. Addition, subtraction and multiplication keep doing so, but for
division the compiler emits a generic bignum sequence that is far slower than the
above: about 287 ns against 12 ns for a 256-bit value divided by `10^18`. That
also restores `constexpr` division for `Int256` and `UInt256`, which the
`_BitInt(256)` conversion had removed because it goes through a
`reinterpret_cast`.

One divmod of a 256-bit value, best of seven, AMD Zen 5, `-march=x86-64-v3`
(`-march=x86-64-v4` is within noise of it - this is scalar integer work):

| divisor | before, x86-64 | before, other platforms | after |
|---|---|---|---|
| `10^18`, one limb | 584.5 ns | 1350.8 ns | 11.9 ns |
| `10^20`, two limbs | 565.1 ns | 1304.5 ns | 25.2 ns |
| `10^40`, three limbs | 372.3 ns | 831.0 ns | 25.3 ns |
| `10^76`, four limbs | 19.2 ns | 26.1 ns | 16.6 ns |
| random 256-bit | 16.1 ns | 17.5 ns | 16.9 ns |
| small | 729.3 ns | 1718.0 ns | 11.7 ns |

The two columns differ because `_BitInt(256)` was only used on x86-64;
everywhere else the shift-and-subtract loop ran, so the improvement there is
larger. Both paths now run the same code, which is one fewer difference between
platforms.

`intDiv` over 2 million `UInt256` values, single thread, end to end:

| query | before | after | |
|---|---|---|---|
| `intDiv(u, 997)` | 1540 ms | 107 ms | 14.4x |
| `intDiv(u, 10^18)` | 1243 ms | 108 ms | 11.5x |
| `modulo(u, 10^18)` | 1145 ms | 106 ms | 10.8x |
| `intDiv(u, 10^20)` | 1209 ms | 136 ms | 8.9x |
| `intDiv(i, 10^18)`, signed | 1126 ms | 151 ms | 7.5x |
| `intDiv(u, 10^40)` | 814 ms | 132 ms | 6.2x |
| `intDiv(small_u, 997)` | 380 ms | 64 ms | 5.9x |
| `intDiv(u, 10^76)` | 118 ms | 114 ms | 1.0x |
| `intDiv(u, v)`, both full width | 158 ms | 157 ms | 1.0x |

The last two are the cases the old algorithm was already good at: when the
divisor is nearly as large as the dividend the quotient has few significant
bits, so its loop exited almost immediately. They are unchanged.

There was no division test coverage to speak of, so this adds three:
`DivisionKnownValues` pins values computed independently, `DivisionInvariants`
checks `q * b + r == a` and the sign and magnitude of the remainder over random
operands of random bit widths, and `DivisionEdgeCases` runs every power of two
and its neighbours, and every power of ten, against each other in both roles -
which covers dividends shorter than the divisor, single-limb divisors, and every
possible normalization shift. During development the new code was also
differentially tested against the algorithm it replaces over 5.2 million
unsigned and 0.9 million signed divisions at 128, 256 and 512 bits.
@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9ee4cd9]

Summary: ✅


AI Review

Summary

This PR replaces the bit-by-bit wide-integer division path with limb-based algorithms, reroutes UInt256 formatting through the new fast divmod helper, and adds focused correctness and performance coverage. The runtime change looks coherent, but one of the new oracle helpers rebuilds wide integers from raw storage order, which breaks the new division tests on big-endian builds.

Findings

⚠️ Majors

  • [src/Common/tests/gtest_wide_integer.cpp:551] toExactInteger iterates num.items directly even though wide::integer stores limbs in native-endian order and expects callers to go through _impl::little / _impl::big. On big-endian targets the helper reconstructs the cpp_int byte-reversed, so DivisionRandomValues and DivisionEdgeCases stop being a trustworthy oracle there. Suggested fix: rebuild the exact value in logical limb order, for example by iterating T::_impl::big(i) or iterating little(i) from the most-significant logical limb down.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 242/247 (97.98%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 29, 2026
Comment thread src/Common/tests/gtest_wide_integer.cpp Resolved
The two `Decimal256` formatting queries in `tests/performance/wide_integer_division.xml`
read the whole 2,000,000-row table, which on the left (master) server takes longer
than the 15 seconds `perf.py` allows a single query: 15.4 s for `toString` on amd
and 41.2 s for `toDecimalString` on arm. The resulting `TIMEOUT_EXCEEDED` is not
caught around the measurement loop, so `perf.py` aborts and the whole shard errors
out. They now read 200,000 rows, which leaves ample headroom. The division queries
keep the full table - the fastest of them already runs in 0.067 s there.

Reports:
https://s3.amazonaws.com/clickhouse-test-reports/PRs/112477/878bc4ede61d23da6e01295212edaa8afa2ff69b/performance_comparison_amd_release_master_head_1_6/report.html
https://s3.amazonaws.com/clickhouse-test-reports/PRs/112477/878bc4ede61d23da6e01295212edaa8afa2ff69b/performance_comparison_arm_release_master_head_4_6/report.html
#112477
`_impl::divide` laid out and trimmed the limb arrays its two algorithms need before
either could start. That setup is a fixed cost, and when both operands occupy a
single limb it exceeds the division itself: 15 ns against the 10 ns the previous
shift-and-subtract loop took, which exited after two iterations because the quotient
had one significant bit. Wide types routinely hold values far smaller than their
width, so the narrow cases now short-circuit ahead of the setup - one limb each goes
to a 64-bit division, two limbs each to `unsigned __int128` - and the limb counts
they need are computed from the operands rather than from the copies, which the
general paths reuse. Both stay usable in constant evaluation.

Per division, averaged over 2^20 operations on a Zen 3:

| case | before this change | after |
| --- | --- | --- |
| both operands one limb | 15.2 ns | 8.6 ns |
| full width / `10^18` | 24.4 ns | 24.4 ns |
| both operands full width | 15.6 ns | 15.7 ns |

The first row was 10.4 ns before the limb-by-limb division, so this also removes the
regression the perf report showed on `bigint_arithm #7`
(`intDiv(toInt256(number + 1), number + 1)`, both operands one limb): +74% on amd
and +23% on arm, on a query stable on master over 946 runs.

Reports:
https://s3.amazonaws.com/clickhouse-test-reports/PRs/112477/df093502267a55bb79cba63b1f9f67bc4b50338a/performance_comparison_amd_release_master_head_3_6/report.html
#112477
Comment thread src/Common/tests/gtest_wide_integer.cpp Resolved
`writeUIntText(UInt256)` in `base/base/itoa.cpp` strips 18-digit blocks off the value
with a division by `10^18` each, and converted the value to `_BitInt(256)` on x86-64
first, on the grounds that the compiler produces better code for it. That was true for
addition and multiplication and is no longer true for division: the compiler emits a
generic bignum sequence, while `UInt256::_impl::divide` now dispatches on the size of
the divisor and handles a single-limb one with a 128 / 64 division per limb. The
conversion is gone, so the same code runs on every platform, and the loop calls
`divide` directly rather than `%` followed by `/`, which halves the number of
divisions.

One `itoa` of a full-width `UInt256`, over 1 million values, AMD Zen 5,
`-march=native`:

| | before | after |
|---|---|---|
| `itoa(UInt256)` | 1063 ns | 87 ns |

The output is unchanged: the new code was differentially tested against repeated
division by ten over every power of two and every power of ten and their neighbours,
`Int256` at its minimum, and 400,000 random values of random bit widths.

This affects every `Int256`/`UInt256` printed in a text format, and the whole part of
every `Decimal256`. `SELECT sum(length(toString(u))) FROM div256` over 2 million
full-width `UInt256` values takes 2092 ms on a single thread before the change; the
end-to-end figure after it is left to the performance test rather than quoted here.

`04652_wide_integer_to_string` covers the boundaries the algorithm turns on: the
powers of two around `2^128`, where the value stops fitting in the `UInt128` path, the
powers of ten around the `10^18` block size, and the extremes of both types.

The performance test gains queries for the paths that were missing from it: printing
a 256-bit integer, rounding and rescaling a `Decimal256`, and `divideDecimal` and
`multiplyDecimal`, which convert their operands to decimal digits one at a time and
so run a division by ten per digit.
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.40% -0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.60% -0.10%

Changed lines: Changed C/C++ lines covered: 218/218 (100.00%) · Uncovered code

Full report · Diff report

@thevar1able
thevar1able marked this pull request as ready for review August 3, 2026 13:26
The division tests only checked the invariants `quotient * b + remainder == a`
and a bound on the remainder. Both are weaker than they look:

- The recomposition is computed in the fixed-width type under test, so it holds
  modulo `2^Bits` rather than exactly. For `UInt256`, a bogus `q = 2` for
  `a = 0`, `b = 2^255` passes, because `q * b` wraps to zero.
- On the signed path only the sign of the remainder was checked, never its
  magnitude, so `a = 10`, `b = -3` with `q = -1`, `r = 7` passes as well.

Compare the quotient and the remainder against `boost::multiprecision::cpp_int`
instead, which is unbounded and truncates toward zero with the remainder taking
the dividend's sign - the same semantics wide integers are expected to have. The
magnitude bound on the remainder then comes for free, and, unlike an `abs` based
check, it needs no special case for a divisor equal to the minimum value.

`boost::multiprecision` is already used for wide integers in
`src/Common/Primality.h`. All 776k dividend and divisor pairs the two division
tests cover agree with the oracle, at a cost of 0.25 seconds for both tests.
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 2376ecec-c274-4189-9584-87d06652ad1d
  • MIRAI run: 5d0cfa8e-4525-4dca-9cb8-a9877ec22f28
  • PR check IDs:
    • clickbench_1826280_1785953336
    • clickbench_1826286_1785953336
    • clickbench_1826292_1785953336
    • tpch_adapted_1_official_1826309_1785953337
    • tpch_adapted_1_official_1826321_1785953336
    • tpch_adapted_1_official_1826328_1785953336

@Algunenano Algunenano self-assigned this Aug 4, 2026
Comment thread base/base/wide_integer_impl.h Resolved
Comment thread base/base/wide_integer_impl.h Resolved
Comment thread base/base/wide_integer_impl.h Resolved
Comment thread base/base/wide_integer_impl.h Outdated
else
{
estimate = static_cast<uint64_t>(top / divisor_high);
estimate_remainder = static_cast<uint64_t>(top % divisor_high);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since top is UInt128 this is promoted to a UInt128 div call and clang will emit __udivti3 on x86, which isn't that good when we know it's dividing by UInt64.

We could introduce something like:

/// 128 / 64 division whose quotient is known to fit in a limb. On x86-64 this is a single `divq`;
/// the portable form promotes to a 128 / 128 division, for which the compiler emits a `__udivti3` call.
constexpr uint64_t divide_128_by_64(uint64_t high, uint64_t low, uint64_t divisor, uint64_t & remainder)
{
#if defined(__x86_64__)
    if (!std::is_constant_evaluated())
    {
        uint64_t quotient;
        __asm__("divq %[divisor]" : "=a"(quotient), "=d"(remainder) : "a"(low), "d"(high), [divisor] "r"(divisor));
        return quotient;
    }
#endif
    const unsigned __int128 dividend = (static_cast<unsigned __int128>(high) << 64) | low;
    remainder = static_cast<uint64_t>(dividend % divisor);
    return static_cast<uint64_t>(dividend / divisor);
}

It's 10-15% faster in my tests.

I couldn't find a better or equivalent way without assembly.

We can use it both here, and in divide_by_single_limb

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we allow inline asm in the codebase?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

Comment thread base/base/itoa.cpp Outdated
x /= large_divisor;
extractDigitPairs(u64_remainder, two_values + current_pos);
/// Returns the quotient and leaves the remainder in its first argument.
const UInt256 quotient = UInt256::_impl::divide(x, large_divisor);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An alternative approach is implementing a divmod_1e18_256 function here:

/// Divides by 10^18 with multiplications only. One limb per step, and each step is a 128 / 64
/// division by a constant, which `divmod_1e18` does with Barrett reduction. The quotient of a step
/// fits in a limb because the remainder carried in from the previous step is below 10^18.
ALWAYS_INLINE inline UInt256 divmod_1e18_256(UInt256 x, uint64_t & remainder)
{
    UInt256 quotient;
    uint64_t r = 0;
    for (int i = 3; i >= 0; --i)
    {
        const unsigned __int128 current = (static_cast<unsigned __int128>(r) << 64) | x.items[UInt256::_impl::little(i)];
        quotient.items[UInt256::_impl::little(i)] = static_cast<uint64_t>(divmod_1e18(current, r));
    }
    remainder = r;
    return quotient;
}

Then just use it:

    /// const UInt256 large_divisor = ...   <- deleted
    UInt256 x = _x;
    while (x.items[UInt256::_impl::little(3)] != 0 || x.items[UInt256::_impl::little(2)] != 0)
    {
        uint64_t block = 0;
        x = divmod_1e18_256(x, block);
        extractDigitPairs(block, two_values + current_pos);
        current_pos += max_multiple_of_hundred_blocks;
    }

Measuring:

Measured

toString of 1M full-width UInt256 values, -march=x86-64-v3, min of 6 interleaved rounds on the now-idle core:

┌──────────────────────┬───────────────┐
│                      │   ns/value    │
├──────────────────────┼───────────────┤
│ PR head              │ 93.97         │
├──────────────────────┼───────────────┤
│ with divmod_1e18_256 │ 73.95 (1.27x) │
└──────────────────────┴───────────────┘

…on, spell out the branches

`base_type` is always `uint64_t`, so the bit-by-bit fallback for other limb
widths was dead code: replace the `if constexpr` with a `static_assert`.

Add `divide_128_by_64` for the 128 / 64 divisions whose quotient is known to
fit in a limb, which is the shape of every division in `divide_by_single_limb`
and of the quotient estimate in step D3 of `divide_knuth`. Written portably it
promotes to a 128 / 128 division and the compiler emits a `__udivti3` call; on
x86-64 the same thing is a single `divq`.

Also replace the ternaries in the normalization and denormalization steps of
`divide_knuth` with an `if` on `shift` around the whole loop, and give the
limb comparison in `divide` its braces.

Measured on 1M random 256-bit divisions, `-march=x86-64-v3`, min of 6
interleaved rounds:

    before  28.8 ns/division
    after   25.9 ns/division  (1.11x)
`writeUIntText` for `UInt256` divided by 10^18 with `UInt256::_impl::divide`,
which is a real 128 / 64 division per limb. `divmod_1e18` already does that
division by the constant 10^18 with Barrett reduction, so `divmod_1e18_256`
walks the four limbs and calls it for each, and the whole block extraction
becomes multiplications.

Measured on `toString` of 1M full-width `UInt256` values, `-march=x86-64-v3`,
min of 6 interleaved rounds:

    before  77.8 ns/value
    after   53.9 ns/value  (1.44x)
{
boost::multiprecision::cpp_int result = 0;
for (size_t i = std::size(num.items); i-- > 0;)
result = (result << 64) | boost::multiprecision::cpp_int(num.items[i]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

toExactInteger is reconstructing the cpp_int from the raw storage order in num.items, but wide::integer deliberately hides that order behind _impl::little/_impl::big because it flips on big-endian builds. On those targets this loop reads the limbs backwards, so the new oracle compares division results against the wrong numeric value and the test can either fail spuriously or miss a real bug. Please rebuild the cpp_int in logical limb order instead of iterating num.items directly.

@thevar1able
thevar1able added this pull request to the merge queue Aug 7, 2026
Merged via the queue into master with commit 74b0711 Aug 7, 2026
351 of 354 checks passed
@thevar1able
thevar1able deleted the faster-wide-integer-division branch August 7, 2026 16:42
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants