Repository navigation
Faster Decimal and 64-bit integer to string conversion - #112457
Conversation
Two independent changes to number formatting.
1. The fractional part of a `Decimal` was written one digit at a time, with a
division and a modulo per digit. For a `Decimal256` with a large scale that is
up to 76 divisions of a 256-bit integer per value, which dominated the cost of
formatting the whole number. It is a field of a known width without any
leading-zero suppression, so it needs neither digit counting nor a general
integer-to-text conversion: the new `writeFixedDigits` emits blocks of eight or
eighteen digits at a time. This part is portable and helps on every platform.
2. `itoa` of a 64-bit value now uses the AVX-512 IFMA algorithm from
Champagne Gareau, J. and Lemire, D., "Converting an Integer to a Decimal String
in Under Two Nanoseconds", Software: Practice and Experience 56(8), 2026,
doi:10.1002/spe.70079, when the CPU supports it. Two `vpmadd52` instructions
produce eight decimal digits without any lookup table, and one masked store
writes exactly the digits that are needed. Only the branch-light variant of the
paper is used; the branch-heavy one is faster only when every value in a batch
has the same number of digits and loses badly otherwise. The translation unit
stays at the baseline architecture, the new functions carry a target attribute
and are reached through a runtime check of the CPU features. For 32 bits and
less the existing jeaiii code is at least as fast and is kept.
Measured with `clickhouse local`, single thread, on a Zen 5, best of five runs:
Decimal256(76) toString 46127 ms -> 2279 ms 20.2x
Decimal256(40) toString 35027 ms -> 4666 ms 7.5x
toDecimalString(D256(40), 40) 35020 ms -> 4683 ms 7.5x
Decimal128(38) toString 1620 ms -> 414 ms 3.9x
toDecimalString(D64(18), 18) 341 ms -> 210 ms 1.6x
Decimal64(18) toString 632 ms -> 396 ms 1.6x
Decimal64(6) toString 481 ms -> 379 ms 1.3x
Decimal128(20) toString 312 ms -> 247 ms 1.3x
Decimal32(9) toString 474 ms -> 388 ms 1.2x
UInt64 random toString 303 ms -> 214 ms 1.4x
UInt128 random toString 445 ms -> 379 ms 1.2x
UInt64 mixed lengths toString 821 ms -> 710 ms 1.2x
UInt256 random toString 10365 ms -> 10346 ms 1.0x
The AVX-512 implementation is deliberately not used for the 18-digit blocks of
`UInt128` and `UInt256`, where several calls into AVX-512 code per value from an
otherwise scalar loop cost more than the cheaper digit generation saves.
`gtest_itoa` compares both implementations against `std::to_chars` and against
a naive reference; `setUseAVX512ItoaForTests` lets one test run cover the
AVX-512 and the portable path on the same machine.
Related: #105725
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Workflow [PR], commit [e18432e] Summary: ✅
AI ReviewSummaryThis PR rewrites Final Verdict
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 425/431 (98.61%) · Uncovered code |
A profile of `toString` of a `Decimal256` with scale 76 showed 91% of the time
inside `writeFixedDigits(UInt256)`, and almost all of it in a chain of `shld $1`
and `or` instructions: dividing a `wide::integer` compiles to a restoring long
division that walks one bit at a time, about 256 iterations per division.
Dividing limb by limb from the most significant limb down needs four 128 by 64
bit divisions instead, each of which the compiler turns into a multiplication by
a reciprocal. The quotient of every step fits into a limb because the previous
remainder is below 10^18. One divmod by 10^18 of a 256-bit value:
wide::integer 513.7 ns
limb by limb 7.4 ns
Converting to `unsigned _BitInt(256)` instead, the way `writeUIntText(UInt256)`
does, was also tried and is twice as slow as `wide::integer` here, so it is not
used.
End to end, `clickhouse local`, single thread, best of three, on a Zen 5:
toString of Decimal256(76) 2346 ms -> 244 ms 9.6x
toString of Decimal256(40) 4795 ms -> 3809 ms 1.3x
toDecimalString(Decimal256(40), 40) 4791 ms -> 3842 ms 1.2x
toString of random UInt256 10540 ms -> 10515 ms 1.0x
Scale 76 gains the most because it needs four of these divisions, while scale 40
needs two and then continues with the Barrett reduction of the 128-bit path.
What remains for a `Decimal256` is no longer in `itoa`: 93% of the time is now in
`DecimalUtils::getWholePart` and `getFractionalPart`, which divide by the scale
multiplier through the same slow `wide::integer` path. That is in
`Core/DecimalFunctions.h` and is used far more widely, so it is left alone here.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`writeFixedDigitsPortable` sent every width through the eight-digit ladder and then copied
part of the result back out of a staging buffer. For one or two digits that is more work
than writing them straight out, which made a small scale such as `Decimal32(2)` slower than
before this branch. The same shortcut covers what is left over after the eight-digit blocks
of the widths 9, 10, 17 and 18, so the common `Decimal` scales gain as well.
This only affects builds that take the portable path: every aarch64 processor, and every x86
processor without AVX-512 IFMA. Where IFMA is available the widths 1 to 19 never reach this
code, which is why it is invisible in the measurements in the branch description.
Measured on aarch64 Neoverse-N1, `clickhouse local`, single thread, best of seven runs:
toString of Decimal32(2) 0.95x -> 1.02x versus master
toString of Decimal32(9) 1.02x -> 1.16x
toString of Decimal64(18) 1.81x -> 1.88x
toString of Decimal128(38) 3.83x -> 4.00x
toDecimalString(Decimal64(18), 18) 1.87x -> 1.92x
formatRow('TSV', Decimal64(9)) 1.07x -> 1.12x
Confirmed on x86-64 as well, by calling `writeFixedDigits` with the AVX-512 implementation
turned off, which is what a pre-IFMA processor does (ns per value, Zen 5):
width 1 2 3 9 10 17 18
before 1.410 1.828 1.914 3.229 3.197 4.605 4.519
after 1.154 1.161 1.553 2.907 2.395 4.172 3.716
The widths 4, 6, 8 and 12 are unchanged. Wider variants were measured and rejected: emitting
digit pairs directly for widths up to four, and a four-digit ladder for widths five to eight.
Each extra branch costs about three per cent, and both lose to this one on the widths that
occur in practice.
Output is unchanged: `gtest_itoa` compares every width from 0 to 20 against a naive reference
on both code paths, and the every-scale sweep of `04652_decimal_to_string_fixed_digits` plus
nine existing decimal tests are byte-identical.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`digitsOfSixteen` built the byte index for `vpermi2b` by widening a 128-bit constant with `_mm512_castsi128_si512`, which leaves the upper lanes undefined. That makes the index a non-constant value in the IR, and MemorySanitizer in clang 21 then falsely reports use-of-uninitialized-value for the permutation: `maskedCheckAVXIndexShadow` checks the truncated index *value* instead of its shadow, and only constant indexes are exempt. Spelling out all 64 bytes keeps the index constant, so the bogus check is not emitted. The generated code is unchanged - the backend narrows the constant back to a 128-bit load. The LLVM fix (llvm/llvm-project#148785) is not in clang 21, which is what CI uses for MSan builds. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112457&sha=88bb28d2c4455f6ffa8bd0659c690deaca14e7a4&name_0=PR&name_1=Unit%20tests%20%28msan%2C%20function_prop_fuzzer%29 Related: #112457 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
MemorySanitizer does not model `_mm512_mask_cvtusepi64_storeu_epi8`: the bytes are written, but their shadow is left untouched. `writeUIntTextFallback` converts into an uninitialized stack buffer, so under MSan every number formatted through the AVX-512 IFMA path looked uninitialized to whatever read it next, and the report surfaced far away - at the `write` of the first log line, which killed the server on startup in the MSan stateless run, and at the `fwrite` of an exception message in the MSan unit test run. Convert in a register and store with `_mm_mask_storeu_epi8`, which is modelled correctly, when building with MSan. It still propagates the shadow of the digits, so genuinely uninitialized input is caught as before. It costs one extra instruction, so the fused store is kept otherwise - the generated code of a normal build is unchanged, down to the same instruction mix. Verified with a randomized cross-check of the AVX-512 path against the scalar one for all integer types and all fixed-digit widths, converting into uninitialized buffers and asserting the shadow of the result with `__msan_test_shadow`. Reports: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112457&sha=88bb28d2c4455f6ffa8bd0659c690deaca14e7a4&name_0=PR&name_1=Stateless%20tests%20%28amd_msan%2C%20flaky%20check%29 https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112457&sha=88bb28d2c4455f6ffa8bd0659c690deaca14e7a4&name_0=PR&name_1=Unit%20tests%20%28msan%29 Related: #112457 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The performance harness runs every query on the reference server too, and allows any single run at most two seconds; a run over fifteen seconds aborts the whole test. The `Decimal256` queries were sized by how long they take with this change, not by how long they take without it, and the reference needs 7.5 to 25 us per row there against 0.26 us per row here. Query 7 of `decimal_to_string` therefore took over sixteen seconds on the reference and killed the test with `Timeout exceeded`, so the whole test reported no results at all. Bring the row counts down until the reference side fits the budget, and record what the counts are for so that they are not raised back. Every query in both tests now runs in at most 0.6 s on the reference. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112457&sha=4405b5c2a3787dc0a7c65c81e926e8da0b293234&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%201%2F6%29 PR: #112457
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 405/413 (98.06%) · Uncovered code |
…tring-ifma # Conflicts: # base/base/itoa.cpp
|
📊 Cloud Performance Report 🟢 AI verdict: This PR is a formatting-only optimization: it adds an AVX-512 fast path for integer-to-string conversion and rewrites decimal fractional formatting, and it ships its own dedicated perf tests for exactly those paths. None of the flagged clickbench aggregations or tpch join queries meaningfully convert integers or decimals to text during execution, so the six ~15-22% improvements and the +6.0% Q28 regression are off this PR's code path and are downgraded to inconclusive. Three very large, work-backed improvements stand under the trust rules — clickbench Q23 (×2.3 faster) and tpch Q7 (×8.1 faster) / Q8 (×2.2 faster) — but these also sit off the formatting path and are far larger than an itoa micro-optimization could produce, so they most likely reflect build or environment differences rather than this change. Net: no credible regression, and no per-query improvement here can be attributed to the diff. clickbench🟢 1 improved · Flagged queries (8 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 2 improved Flagged queries (2 of 22)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. Debug info
|
…nto the whole part
`toDecimalString` rounds the value to the requested number of fractional digits, but the rounding
happened in `writeDecimalFractional`, after `writeText` had already written the whole part, so a
carry out of the fractional part was dropped: `toDecimalString(toDecimal64('9.995', 3), 2)` returned
`9.00` instead of `10.00`, `toDecimalString(toDecimal32('99.95', 2), 1)` returned `99.0` instead of
`100.0`, and `toDecimalString(toDecimal256('-0.5', 2), 0)` returned `-0.` instead of `-1.`. The
documented contract is that the function rounds, so this was a real defect, and it predates the rest
of this branch.
`writeText` now rounds the whole value before splitting it into a whole and a fractional part, and
`writeDecimalFractional` no longer rounds at all - a `chassert` states the invariant that the caller
has already narrowed the value to the requested width. The rounding is unchanged otherwise: still
half away from zero, and still deciding on the first dropped digit, which is the same as comparing
the dropped remainder against half of the dropped field. Written that way it takes one division
rather than two, which matters for a `Decimal256`, where dividing a `wide::integer` costs about half
a microsecond.
The sign of a value that rounds to zero is preserved as before, so
`toDecimalString(toDecimal64('-0.004', 3), 2)` still returns `-0.00`.
`04652_decimal_to_string_fixed_digits` recorded the old output for
`toDecimalString(toDecimal256('-0.5', 2), 0)` and now asserts the rounded one.
`add-test` assigned `04821` before this branch took the current `master`, which already has two tests with that number.
|
🕵 The two failures on Stress test (arm_debug) — Upgrade check (amd_release) — Current |
|
No fix PR exists, so I will open one. The throw-site comment you quoted describes a different case: this failure is not the BACKUP/RESTORE path. The stack in
Regression from #87206 ( The name is still available where the info is parsed ( The consequence is not only a log line: both tables in the report went readonly ( I will link the PR here. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units2449 translation units recompiled, 13089 s compile time in total, 2449 of them have a recent master baseline. |
|
Fix is up: #114980. Not the
#114980 passes the name at both sites, which is the remedy you used in |
|
🕵 Merged current |
…ecated syntax
A table created with the deprecated positional syntax
(ENGINE = ReplicatedMergeTree(date, key, granularity) under
allow_deprecated_syntax_for_merge_tree) uses date-based V0 part names.
MergeTreePartInfo::getPartNameAndCheckFormat cannot produce such a name,
because getPartNameV0 needs the min/max DayNum that MergeTreePartInfo does
not carry, so it throws BAD_DATA_PART_NAME unconditionally.
Two ActiveDataPartSet entry points accept only a MergeTreePartInfo and must
therefore synthesize a name that way: tryAddPart and add(info, Strings *).
Each had exactly one production caller, and both callers already held the
part name and discarded it:
* ReplicatedMergeTreeQueue::getPartNamesToMutate builds mutation.parts_to_do.
The throw aborted mutationsUpdatingTask and left parts_to_do empty, so the
mutation was reported as done on a replica that had not applied it. With
mutations_sync = 2 the ALTER returned success while that replica still
served pre-mutation values. Regressed by ClickHouse#87206, which changed
QueueEntryRepresentation::produced_parts from a vector of names to a vector
of infos.
* StorageReplicatedMergeTree::checkPartsImpl builds the set of empty
unexpected parts on disk. The throw aborted ReplicatedMergeTreeAttachThread
and left the table readonly. Regressed by ClickHouse#103537, which replaced
tryAdd(name, &reason) with add(info, name, ...).
Both failures appear in a single Upgrade check report on ClickHouse#112457. Pass the
name that is already in hand at both call sites instead. V0 name formatting is
untouched, and behaviour on current-format tables is provably unchanged
because the name-taking overload re-parses the name into the identical info
and runs the same addImpl. This is the remedy alexey-milovidov used in
536b611 for the ATTACH PARTITION instance of
the same defect, which added ActiveDataPartSet::tryAdd(const String &).
dropped_parts is deliberately left holding infos only:
removePartAndCoveredParts(info) is getPartsCoveredBy + remove, neither of
which regenerates a name.
The V0 gap in MergeTreeData::restorePartFromBackup that the comment at the
throw site describes is a different code path, absent from both stacks here,
and is not addressed.
Testing: 04907_mutation_parts_to_do_deprecated_syntax asserts parts_to_do on
the frozen replica and fails on master with "parts to do 0". checkPartsImpl's
state requires fabricating parts on disk, which is not allowed in a stateless
test, so that half is covered by three V0 cases in gtest_active_data_part_set,
all of which fail with this change reverted.
Closes: #105725
The fractional part of a
Decimalwas written one digit at a time, with a division per digit — up to 76 divisions of a 256-bit integer for a singleDecimal256value. It is a field of a known width, so it is now emitted in blocks of eight or eighteen digits instead, with one- and two-digit fields written directly. The remaining divisions by 10^18 are done limb by limb, because dividing awide::integercompiles to a long division that walks one bit at a time (513 ns per divmod, against 7 ns limb by limb). All of this is portable.Separately,
itoaof a 64-bit value uses the AVX-512 IFMA algorithm from Champagne Gareau, J. and Lemire, D., "Converting an Integer to a Decimal String in Under Two Nanoseconds", Software: Practice and Experience 56(8), 2026, doi:10.1002/spe.70079, behind a runtime CPU check.Results
clickhouse local, single thread, best of five runs, AMD Zen 5 (so the AVX-512 path is active),-march=x86-64-v3build, against a binary built from the same tree without these changes:toStringofDecimal256(76)toStringofDecimal256(40)toDecimalString(Decimal256(40), 40)toStringofDecimal128(38)toDecimalString(Decimal64(18), 18)toStringofDecimal64(18)toStringofDecimal64(6)toStringofDecimal128(20)toStringofDecimal32(9)toStringof randomUInt64toStringof randomUInt128toStringofUInt64of mixed lengthstoStringof randomUInt256formatRow('TSV', ...)ofDecimal64(9)The
Decimal256andUInt256rows were re-measured after the second commit (best of three); the others are unaffected by it. New perf testsdecimal_to_string.xmlanduint64_to_string.xmlcover the same ground; the existingdecimal_format.xmlonly had a singleDecimal64(6)query.Without AVX-512 IFMA
Every aarch64 processor and every x86 processor without IFMA takes the portable path, where the
Decimalwork applies in full butitoaof a 64-bit value is unchanged. On aarch64 Neoverse-N1, best of seven runs, against master:toStringofDecimal128(38)toDecimalString(Decimal64(18), 18)toStringofDecimal64(18)toStringofDecimal32(9)toStringofDecimal64(6)formatRow('TSV', ...)ofDecimal64(9)toStringofDecimal32(2)The third commit exists because the first one made the smallest scales slightly slower on this path —
Decimal32(2)was at 0.95x — which is invisible on a machine with IFMA, since there the widths 1 to 19 never reach the portable code at all. Writing one- and two-digit fields directly, instead of running them through the eight-digit ladder and copying part of the result back out, fixes that and also speeds up what is left over after the eight-digit blocks of the widths 9, 10, 17 and 18. Confirmed on x86-64 as well, by callingwriteFixedDigitswith the AVX-512 implementation turned off (ns per value, Zen 5): width 2 goes from 1.828 to 1.161, width 10 from 3.197 to 2.395, width 18 from 4.519 to 3.716, and the widths 4, 6, 8 and 12 are unchanged.A rounding fix
toDecimalStringdocuments that it rounds the value to the requested number of fractional digits, but it rounded the fractional part after the whole part had already been written, so a carry never crossed the decimal point.toDecimalString(toDecimal64('9.995', 3), 2)returned9.00instead of10.00,toDecimalString(toDecimal32('99.95', 2), 1)returned99.0instead of100.0, andtoDecimalString(toDecimal256('-0.5', 2), 0)returned-0.instead of-1.. That predates this change; it is fixed here because the rounding now happens on the whole value, before it is split into a whole and a fractional part, andwriteDecimalFractionalno longer rounds at all. It costs one big-integer division instead of two, and it is covered by04907_to_decimal_string_rounding_carry.What is left
What remains for a
Decimal256is no longer initoa: 93% of the time is now inDecimalUtils::getWholePartandgetFractionalPart, which divide by the scale multiplier through the same slowwide::integerpath. That is inCore/DecimalFunctions.hand used far more widely, so it is left alone here.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Formatting
Decimalvalues as text is much faster — up to 190 times for aDecimal256with a large scale, and about 1.6 times for aDecimal64. On processors with AVX-512 IFMA, converting 64-bit integers to text is about 1.4 times faster. Also fixed the rounding oftoDecimalString, which dropped a carry out of the fractional part:toDecimalString(toDecimal64('9.995', 3), 2)returned9.00and now returns10.00.