[all-commits] [llvm/llvm-project] c06d0f: [libc] Optimize BigInt→decimal in IntegerToString ...

Simon Tatham via All-commits all-commits at lists.llvm.org
Tue Feb 4 00:58:03 PST 2025


  Branch: refs/heads/main
  Home:   https://github.com/llvm/llvm-project
  Commit: c06d0ff806b72b1cfbca6306a2bc4f5f2922b01b
      https://github.com/llvm/llvm-project/commit/c06d0ff806b72b1cfbca6306a2bc4f5f2922b01b
  Author: Simon Tatham <simon.tatham at arm.com>
  Date:   2025-02-04 (Tue, 04 Feb 2025)

  Changed paths:
    M libc/src/__support/integer_to_string.h
    M libc/test/src/__support/integer_to_string_test.cpp

  Log Message:
  -----------
  [libc] Optimize BigInt→decimal in IntegerToString (#123580)

When IntegerToString converts a BigInt into decimal, it determines each
digit by computing `n % 10` and then resets n to `n / 10`, until the
number becomes zero. The div and mod operations are done using
`BigInt::divide_unsigned`, which uses the simplest possible bit-by-bit
iteration, which is a slow algorithm in general, but especially so if
the divisor 10 must first be promoted to a BigInt the same size as the
dividend. The effect is to make each division take quadratic time, so
that the overall decimal conversion is cubic – and the division is
quadratic in the number of _bits_, so the constant of proportionality is
also large.

In this patch I've provided custom code to extract decimal digits much
faster, based on knowing that the divisor is always 10, and processing a
word at a time. So each digit extraction is linear-time with a much
smaller constant of proportionality.

Full comments are in the code. The general strategy is to do the
reduction mod 10 first to determine the output digit; then subtract it
off, so that what's left is guaranteed to be an exact multiple of 10;
and finally divide by 10 using modular-arithmetic techniques rather than
reciprocal-approximation-based ordinary integer division.

I didn't find any existing tests of IntegerToString on a BigInt, so I've
added one.



To unsubscribe from these emails, change your notification settings at https://github.com/llvm/llvm-project/settings/notifications


More information about the All-commits mailing list