pgsql: Optimise numeric multiplication using base-NBASE^2 arithmetic.

From: Dean Rasheed <dean(dot)a(dot)rasheed(at)gmail(dot)com>
To: pgsql-committers(at)lists(dot)postgresql(dot)org
Subject: pgsql: Optimise numeric multiplication using base-NBASE^2 arithmetic.
Date: 2024-08-15 09:37:24
Message-ID: E1seWv6-004G6Q-Fc@gemulon.postgresql.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-committers

Optimise numeric multiplication using base-NBASE^2 arithmetic.

Currently mul_var() uses the schoolbook multiplication algorithm,
which is O(n^2) in the number of NBASE digits. To improve performance
for large inputs, convert the inputs to base NBASE^2 before
multiplying, which effectively halves the number of digits in each
input, theoretically speeding up the computation by a factor of 4. In
practice, the actual speedup for large inputs varies between around 3
and 6 times, depending on the system and compiler used. In turn, this
significantly reduces the runtime of the numeric_big regression test.

For this to work, 64-bit integers are required for the products of
base-NBASE^2 digits, so this works best on 64-bit machines, on which
it is faster whenever the shorter input has more than 4 or 5 NBASE
digits. On 32-bit machines, the additional overheads, especially
during carry propagation and the final conversion back to base-NBASE,
are significantly higher, and it is only faster when the shorter input
has more than around 50 NBASE digits. When the shorter input has more
than 6 NBASE digits (so that mul_var_short() cannot be used), but
fewer than around 50 NBASE digits, there may be a noticeable slowdown
on 32-bit machines. That seems to be an acceptable tradeoff, given the
performance gains for other inputs, and the effort that would be
required to maintain code specifically targeting 32-bit machines.

Joel Jacobson and Dean Rasheed.

Discussion: https://postgr.es/m/9d8a4a42-c354-41f3-bbf3-199e1957db97%40app.fastmail.com

Branch
------
master

Details
-------
https://git.postgresql.org/pg/commitdiff/8dc28d7eb868b6ce5a51614628bf46fc63c7e90c

Modified Files
--------------
src/backend/utils/adt/numeric.c | 224 +++++++++++++++++++++++++++-------------
1 file changed, 150 insertions(+), 74 deletions(-)

Browse pgsql-committers by date

  From Date Subject
Next Message Robert Haas 2024-08-15 14:45:26 pgsql: Do not hardcode PG_PROTOCOL_LATEST in NegotiateProtocolVersion
Previous Message Dean Rasheed 2024-08-15 09:35:28 pgsql: Extend mul_var_short() to 5 and 6-digit inputs.