From: Joel Jacobson <joel@compiler.org>
To: pgsql-hackers <pgsql-hackers@postgresql.org>
Subject: [PATCH] Use 128-bit math to accelerate numeric division, when 8 < divisor digits <= 16
Date: Sun, 22 Jan 2023 09:41:01 -0400
Message-ID: <b7a5893d-af18-4c0b-8918-96de5f1bbf39@app.fastmail.com> (raw)
Hi,
On platforms where we support 128bit integers, we could accelerate division
when the number of digits in the divisor is larger than 8 and less than or
equal to 16 digits, i.e. when the divisor that fits in a 64-bit integer but would
not fit in a 32-bit integer.
This patch adds div_var_int64(), which is similar to the existing div_var_int(),
but accepts a 64-bit divisor instead of a 32-bit divisor.
The new function is used within div_var() and div_var_fast().
To measure the effect, we need a volatile wrapper function for numeric_div(),
to avoid it being cached since it's immutable:
CREATE OR REPLACE FUNCTION numeric_div_volatile(numeric,numeric)
RETURNS numeric LANGUAGE internal AS 'numeric_div';
We can then use generate_series() to measure the execution time for lots of
executions. This does not account for the overhead of generate_series() and
count(), but that's okay since the overhead is the same in both measurements,
so the relative difference is still correct.
--
-- Division when the divisor is 8 digits should be unchanged:
--
EXPLAIN ANALYZE
SELECT count(numeric_div_volatile(
repeat('1',131071)::numeric,
repeat('3',8)::numeric
)) FROM generate_series(1,1e4);
-- Execution Time: 1633.722 ms (HEAD)
-- Execution Time: 1680.228 ms (div_var_int64.patch)
--
-- Division when the divisor is 9 digits should be faster:
--
EXPLAIN ANALYZE
SELECT count(numeric_div_volatile(
repeat('1',131071)::numeric,
repeat('3',9)::numeric
)) FROM generate_series(1,1e4);
-- Execution Time: 5444.755 ms (HEAD)
-- Execution Time: 1604.967 ms (div_var_int64.patch)
--
-- Division when the divisor is 16 digits should also be faster:
--
EXPLAIN ANALYZE
SELECT count(numeric_div_volatile(
repeat('1',131071)::numeric,
repeat('3',16)::numeric
)) FROM generate_series(1,1e4);
-- Execution Time: 6072.683 ms (HEAD)
-- Execution Time: 3215.686 ms (div_var_int64.patch)
--
-- Division when the divisor is 17 digits should be unchanged:
--
EXPLAIN ANALYZE
SELECT count(numeric_div_volatile(
repeat('1',131071)::numeric,
repeat('3',17)::numeric
)) FROM generate_series(1,1e4);
-- Execution Time: 6948.150 ms (HEAD)
-- Execution Time: 7010.544 ms (div_var_int64.patch)
--
-- Same tests as above, but with a single digit dividend,
-- and 1e7 executions instead of just 1e4.
--
--
-- Division when the divisor is 8 digits should be unchanged:
--
EXPLAIN ANALYZE
SELECT count(numeric_div_volatile(
1,
repeat('3',8)::numeric
)) FROM generate_series(1,1e7);
-- Execution Time: 1827.567 ms (HEAD)
-- Execution Time: 1828.029 ms (div_var_int64.patch)
--
-- Division when the divisor is 9 digits should be faster:
--
EXPLAIN ANALYZE
SELECT count(numeric_div_volatile(
1,
repeat('3',9)::numeric
)) FROM generate_series(1,1e7);
-- Execution Time: 2314.851 ms (HEAD)
-- Execution Time: 1886.170 ms (div_var_int64.patch)
--
-- Division when the divisor is 16 digits should also be faster:
--
EXPLAIN ANALYZE
SELECT count(numeric_div_volatile(
1,
repeat('3',16)::numeric
)) FROM generate_series(1,1e7);
-- Execution Time: 2244.009 ms (HEAD)
-- Execution Time: 1968.148 ms (div_var_int64.patch)
--
-- Division when the divisor is 17 digits should be unchanged:
--
EXPLAIN ANALYZE
SELECT count(numeric_div_volatile(
1,
repeat('3',17)::numeric
)) FROM generate_series(1,1e7);
-- Execution Time: 2334.896 ms (HEAD)
-- Execution Time: 2338.141 ms (div_var_int64.patch)
The graph below shows the effect on execution time for numeric_div(),
and also looks at numeric_mod() since it's a heavy user of numeric_div().
The graph was produced by generating 100 random numeric integer values
for each combination of number of dividend/divisor digits between 1 to 20.
In total, that's 20*20*100*2=80000 test values.
As expected, the ceiling for the fast short division is lifted from 8 to 16 divisor digits,
and speedups for modulus is noticed in the same region.
The graph was produced using results from pg-timeit [1] and R for the plotting.
[1] https://github.com/joelonsql/pg-timeit
/Joel
Attachments:image.png (image/png, 117.8K) downloadview imagediv_var_int64.patch (application/octet-stream, 6.2K) downloaddiff --git a/src/backend/utils/adt/numeric.c b/src/backend/utils/adt/numeric.cindex a6409ecbee..30b0e339ff 100644--- a/src/backend/utils/adt/numeric.c+++ b/src/backend/utils/adt/numeric.c@@ -554,6 +554,10 @@ static void div_var_fast(const NumericVar *var1, const NumericVar *var2,
NumericVar *result, int rscale, bool round);
static void div_var_int(const NumericVar *var, int ival, int ival_weight,
NumericVar *result, int rscale, bool round);
+#ifdef HAVE_INT128+static void div_var_int64(const NumericVar *var, int64 ival, int ival_weight,+ NumericVar *result, int rscale, bool round);+#endif
static int select_div_scale(const NumericVar *var1, const NumericVar *var2);
static void mod_var(const NumericVar *var1, const NumericVar *var2,
NumericVar *result);
@@ -8484,7 +8488,32 @@ div_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result,
/*
* If the divisor has just one or two digits, delegate to div_var_int(),
* which uses fast short division.
+ *+ * On platforms with 128-bit integer support, and if the divisor has+ * three or four digits, delegate to div_var_int64(),+ * which also uses fast short division.
*/
+ #ifdef HAVE_INT128+ if (var2ndigits <= 4)+ {+ int64 idivisor;+ int idivisor_weight;++ idivisor = var2->digits[0];+ idivisor_weight = var2->weight;+ for (i = 1; i < var2ndigits; i++)+ {+ idivisor *= NBASE;+ idivisor += var2->digits[i];+ idivisor_weight--;+ }+ if (var2->sign == NUMERIC_NEG)+ idivisor = -idivisor;++ div_var_int64(var1, idivisor, idivisor_weight, result, rscale, round);+ return;+ }+ #else
if (var2ndigits <= 2)
{
int idivisor;
@@ -8503,6 +8532,7 @@ div_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result,
div_var_int(var1, idivisor, idivisor_weight, result, rscale, round);
return;
}
+ #endif
/*
* Otherwise, perform full long division.
@@ -8774,7 +8804,32 @@ div_var_fast(const NumericVar *var1, const NumericVar *var2,
/*
* If the divisor has just one or two digits, delegate to div_var_int(),
* which uses fast short division.
+ *+ * On platforms with 128-bit integer support, and if the divisor has+ * three or four digits, delegate to div_var_int64(),+ * which also uses fast short division.
*/
+ #ifdef HAVE_INT128+ if (var2ndigits <= 4)+ {+ int64 idivisor;+ int idivisor_weight;++ idivisor = var2->digits[0];+ idivisor_weight = var2->weight;+ for (i = 1; i < var2ndigits; i++)+ {+ idivisor *= NBASE;+ idivisor += var2->digits[i];+ idivisor_weight--;+ }+ if (var2->sign == NUMERIC_NEG)+ idivisor = -idivisor;++ div_var_int64(var1, idivisor, idivisor_weight, result, rscale, round);+ return;+ }+ #else
if (var2ndigits <= 2)
{
int idivisor;
@@ -8793,6 +8848,7 @@ div_var_fast(const NumericVar *var1, const NumericVar *var2,
div_var_int(var1, idivisor, idivisor_weight, result, rscale, round);
return;
}
+ #endif
/*
* Otherwise, perform full long division.
@@ -9182,6 +9238,118 @@ div_var_int(const NumericVar *var, int ival, int ival_weight,
}
+/*+ * div_var_int64() -+ *+ * Divide a numeric variable by a 64-bit integer with the specified weight.+ * The quotient var / (ival * NBASE^ival_weight) is stored in result.+ */+static void+div_var_int64(const NumericVar *var, int64 ival, int ival_weight,+ NumericVar *result, int rscale, bool round)+{+ NumericDigit *var_digits = var->digits;+ int var_ndigits = var->ndigits;+ int res_sign;+ int res_weight;+ int res_ndigits;+ NumericDigit *res_buf;+ NumericDigit *res_digits;+ uint64 divisor;+ int i;++ /* Guard against division by zero */+ if (ival == 0)+ ereport(ERROR,+ errcode(ERRCODE_DIVISION_BY_ZERO),+ errmsg("division by zero"));++ /* Result zero check */+ if (var_ndigits == 0)+ {+ zero_var(result);+ result->dscale = rscale;+ return;+ }++ /*+ * Determine the result sign, weight and number of digits to calculate.+ * The weight figured here is correct if the emitted quotient has no+ * leading zero digits; otherwise strip_var() will fix things up.+ */+ if (var->sign == NUMERIC_POS)+ res_sign = ival > 0 ? NUMERIC_POS : NUMERIC_NEG;+ else+ res_sign = ival > 0 ? NUMERIC_NEG : NUMERIC_POS;+ res_weight = var->weight - ival_weight;+ /* The number of accurate result digits we need to produce: */+ res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;+ /* ... but always at least 1 */+ res_ndigits = Max(res_ndigits, 1);+ /* If rounding needed, figure one more digit to ensure correct result */+ if (round)+ res_ndigits++;++ res_buf = digitbuf_alloc(res_ndigits + 1);+ res_buf[0] = 0; /* spare digit for later rounding */+ res_digits = res_buf + 1;++ /*+ * Now compute the quotient digits. This is the short division algorithm+ * described in Knuth volume 2, section 4.3.1 exercise 16, except that we+ * allow the divisor to exceed the internal base.+ *+ * In this algorithm, the carry from one digit to the next is at most+ * divisor - 1. Therefore, while processing the next digit, carry may+ * become as large as divisor * NBASE - 1, and so it requires a 128-bit+ * integer if this exceeds ULONG_MAX.+ */+ divisor = i64abs(ival);++ if (divisor <= ULONG_MAX / NBASE)+ {+ /* carry cannot overflow 64 bits */+ uint64 carry = 0;++ for (i = 0; i < res_ndigits; i++)+ {+ carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);+ res_digits[i] = (NumericDigit) (carry / divisor);+ carry = carry % divisor;+ }+ }+ else+ {+ /* carry may exceed 64 bits */+ uint128 carry = 0;++ for (i = 0; i < res_ndigits; i++)+ {+ carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);+ res_digits[i] = (NumericDigit) (carry / divisor);+ carry = carry % divisor;+ }+ }++ /* Store the quotient in result */+ digitbuf_free(result->buf);+ result->ndigits = res_ndigits;+ result->buf = res_buf;+ result->digits = res_digits;+ result->weight = res_weight;+ result->sign = res_sign;++ /* Round or truncate to target rscale (and set result->dscale) */+ if (round)+ round_var(result, rscale);+ else+ trunc_var(result, rscale);++ /* Strip leading/trailing zeroes */+ strip_var(result);+}++
/*
* Default scale selection for division
*
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-hackers@postgresql.org
Cc: joel@compiler.org
Subject: Re: [PATCH] Use 128-bit math to accelerate numeric division, when 8 < divisor digits <= 16
In-Reply-To: <b7a5893d-af18-4c0b-8918-96de5f1bbf39@app.fastmail.com>
References: <b7a5893d-af18-4c0b-8918-96de5f1bbf39@app.fastmail.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox