Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions Lib/test/test_decimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -1335,6 +1335,53 @@ class PyFormatTest(FormatTest, unittest.TestCase):
class ArithmeticOperatorsTest:
'''Unit tests for all arithmetic operators, binary and unary.'''

def test_int64_operands(self):
Decimal = self.decimal.Decimal

class SubDecimal(Decimal):
pass

class SubInt(int):
pass

operands = (
-(2**63) - 1, -(2**63), -1, 0, 2**63 - 1, 2**63,
True, SubInt(7),
)
for cls in (Decimal, SubDecimal):
d = cls("-1.25")
for n in operands:
for op in (operator.add, operator.sub, operator.mul,
operator.truediv, operator.floordiv, operator.mod):
for left, right in ((d, n), (n, d)):
with self.subTest(cls=cls, n=n, op=op, left=left):
with self.decimal.localcontext(prec=6) as ctx:
ctx.clear_traps()
ctx.clear_flags()
expected = op(Decimal(left), Decimal(right))
flags = ctx.flags.copy()
ctx.clear_flags()
actual = op(left, right)
self.assertIs(type(actual), Decimal)
self.assertEqual(
actual.as_tuple(), expected.as_tuple()
)
self.assertEqual(ctx.flags.copy(), flags)

def test_int_operand_traps(self):
dec = self.decimal
with dec.localcontext(prec=2) as ctx:
ctx.traps[dec.Inexact] = True
ctx.clear_flags()
with self.assertRaises(dec.Inexact):
dec.Decimal(2**63 - 1) - dec.Decimal("0.1")
expected_flags = ctx.flags.copy()
ctx.clear_flags()
with self.assertRaises(dec.Inexact):
(2**63 - 1) - dec.Decimal("0.1")
self.assertEqual(ctx.flags.copy(), expected_flags)
self.assertTrue(ctx.flags[dec.Inexact])

def test_addition(self):
Decimal = self.decimal.Decimal

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Speed up arithmetic between a :class:`~decimal.Decimal` and an :class:`int`
that fits in a signed 64-bit integer.
58 changes: 58 additions & 0 deletions Modules/_decimal/_decimal.c
Original file line number Diff line number Diff line change
Expand Up @@ -4491,6 +4491,38 @@ nm_##MPDFUNC(PyObject *self) \
return result; \
}

typedef void (*mpd_binaryfunc)(mpd_t *, const mpd_t *, const mpd_t *,
const mpd_context_t *, uint32_t *);

static PyObject *
dec_binop_int64(decimal_state *state, PyObject *context, mpd_binaryfunc op,
PyObject *decimal, int64_t value, int reflected)
{
mpd_uint_t data[_Py_DEC_MINALLOC];
mpd_t integer = {
.flags = MPD_STATIC | MPD_STATIC_DATA,
.alloc = _Py_DEC_MINALLOC,
.data = data,
};
uint32_t status = 0;
mpd_qset_i64_exact(&integer, value, &status);
if (status && dec_addstatus(context, status)) {
mpd_del(&integer);
return NULL;
}
PyObject *result = dec_alloc(state);
if (result != NULL) {
const mpd_t *a = reflected ? &integer : MPD(decimal);
const mpd_t *b = reflected ? MPD(decimal) : &integer;
op(MPD(result), a, b, CTX(context), &status);
if (dec_addstatus(context, status)) {
Py_CLEAR(result);
}
}
mpd_del(&integer);
return result;
}

/* Binary number method that uses default module context. */
#define Dec_BinaryNumberMethod(MPDFUNC) \
static PyObject * \
Expand All @@ -4503,6 +4535,32 @@ nm_##MPDFUNC(PyObject *self, PyObject *other) \
\
decimal_state *state = find_state_left_or_right(self, other); \
CURRENT_CONTEXT(state, context) ; \
if (PyDec_CheckExact(state, self) && \
PyDec_CheckExact(state, other)) { \
if ((result = dec_alloc(state)) == NULL) { \
return NULL; \
} \
MPDFUNC(MPD(result), MPD(self), MPD(other), \
CTX(context), &status); \
if (dec_addstatus(context, status)) { \
Py_DECREF(result); \
return NULL; \
} \
return result; \
} \
int reflected = PyLong_CheckExact(self); \
if (reflected || PyLong_CheckExact(other)) { \
PyObject *integer = reflected ? self : other; \
int overflow; \
long long value = \
PyLong_AsLongLongAndOverflow(integer, &overflow); \
if (!overflow) { \
Py_BUILD_ASSERT(sizeof(value) == sizeof(int64_t)); \
return dec_binop_int64(state, context, MPDFUNC, \
reflected ? other : self, \
value, reflected); \
} \
} \
CONVERT_BINOP(&a, &b, self, other, context); \

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.

And here you check both ops against for being PyLong and PyDec...

Please include in your micro-benchmarks also cases, when both operands are decimals.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Pushed 5ce2e26. Dec_BinaryNumberMethod now does the same thing as Dec_UnaryNumberMethod: if both operands are exact Decimal it calls MPDFUNC directly, so that case doesn't go through the PyLong_CheckExact checks or CONVERT_BINOP anymore.

I reran the micro benchmarks with PGO+LTO against main at d88a6b9 (M4 Pro, Clang 21, libmpdec 4.0.1, pyperf -p 20 -w 1 -n 3):

+---------------------------+------------+-----------------------+
| Benchmark                 | micro_base | micro_patched         |
+===========================+============+=======================+
| dec_add_dec               | 38.9 ns    | 38.4 ns: 1.01x faster |
+---------------------------+------------+-----------------------+
| dec_truediv_dec           | 57.2 ns    | 55.8 ns: 1.02x faster |
+---------------------------+------------+-----------------------+
| dec_floordiv_dec          | 44.5 ns    | 43.6 ns: 1.02x faster |
+---------------------------+------------+-----------------------+
| dec_mod_dec               | 44.4 ns    | 41.7 ns: 1.06x faster |
+---------------------------+------------+-----------------------+
| dec_dec_mixed4_small      | 167 ns     | 164 ns: 1.02x faster  |
+---------------------------+------------+-----------------------+
| dec_dec_mixed4_prec28     | 238 ns     | 233 ns: 1.02x faster  |
+---------------------------+------------+-----------------------+
| dec_dec_mixed4_prec100    | 642 ns     | 640 ns: 1.00x faster  |
+---------------------------+------------+-----------------------+
| dec_add_int31             | 61.9 ns    | 47.9 ns: 1.29x faster |
+---------------------------+------------+-----------------------+
| int31_sub_dec             | 66.9 ns    | 53.8 ns: 1.24x faster |
+---------------------------+------------+-----------------------+
| dec_mul_int31             | 55.9 ns    | 40.6 ns: 1.38x faster |
+---------------------------+------------+-----------------------+
| int31_truediv_dec         | 84.4 ns    | 70.4 ns: 1.20x faster |
+---------------------------+------------+-----------------------+
| dec_floordiv_int31        | 68.0 ns    | 51.6 ns: 1.32x faster |
+---------------------------+------------+-----------------------+
| dec_mod_int31             | 68.3 ns    | 50.7 ns: 1.35x faster |
+---------------------------+------------+-----------------------+
| dec_int31_mixed4_small    | 269 ns     | 210 ns: 1.28x faster  |
+---------------------------+------------+-----------------------+
| dec_int62_mixed4_small    | 266 ns     | 205 ns: 1.29x faster  |
+---------------------------+------------+-----------------------+
| dec_int84_overflow_mixed4 | 334 ns     | 344 ns: 1.03x slower  |
+---------------------------+------------+-----------------------+
| dec_int62_mixed4_prec28   | 355 ns     | 291 ns: 1.22x faster  |
+---------------------------+------------+-----------------------+
| Geometric mean            | (ref)      | 1.13x faster          |
+---------------------------+------------+-----------------------+

Benchmark hidden because not significant (2): dec_sub_dec, dec_mul_dec

Plain Decimal op Decimal comes out about the same as main, maybe 1% faster. I wouldn't trust the 1.06x on %, it's probably just noise between the two PGO builds. The dec_int84_overflow_mixed4 slowdown is real though, around 2.5 ns per op. Ints bigger than int64 now go through PyLong_AsLongLongAndOverflow first and only then fall back to PyLong_Export. I thought that was noise in the earlier run on the issue, but it isn't. Decimal subclasses also pay an extra check (~1 ns) before falling through to CONVERT_BINOP.

test_decimal passes on the PGO+LTO build, on --with-pydebug with -R 3:3, and on --disable-gil.

bm_decimal_all.py
import decimal
import pyperf


def run_dec_dec_loop(a, b, op_kind, loops):
    t0 = pyperf.perf_counter()
    if op_kind == "add":
        for _ in range(loops):
            a + b
    elif op_kind == "sub":
        for _ in range(loops):
            a - b
    elif op_kind == "mul":
        for _ in range(loops):
            a * b
    elif op_kind == "truediv":
        for _ in range(loops):
            a / b
    elif op_kind == "floordiv":
        for _ in range(loops):
            a // b
    elif op_kind == "mod":
        for _ in range(loops):
            a % b
    elif op_kind == "mixed4":
        for _ in range(loops):
            a + b
            b - a
            a * b
            b / a
    return pyperf.perf_counter() - t0


def make_dec_dec_op(a_str, b_str, op_kind, prec=None):
    def bench(loops):
        a = decimal.Decimal(a_str)
        b = decimal.Decimal(b_str)
        if prec is None:
            return run_dec_dec_loop(a, b, op_kind, loops)
        with decimal.localcontext() as ctx:
            ctx.prec = prec
            return run_dec_dec_loop(a, b, op_kind, loops)
    return bench


def run_dec_int_loop(d, n, op_kind, loops):
    t0 = pyperf.perf_counter()
    if op_kind == "add":
        for _ in range(loops):
            d + n
    elif op_kind == "rsub":
        for _ in range(loops):
            n - d
    elif op_kind == "mul":
        for _ in range(loops):
            d * n
    elif op_kind == "rtruediv":
        for _ in range(loops):
            n / d
    elif op_kind == "floordiv":
        for _ in range(loops):
            d // n
    elif op_kind == "mod":
        for _ in range(loops):
            d % n
    elif op_kind == "mixed4":
        for _ in range(loops):
            d + n
            n - d
            d * n
            n / d
    return pyperf.perf_counter() - t0


def make_dec_int_op(d_str, n_val, op_kind, prec=None):
    def bench(loops):
        d = decimal.Decimal(d_str)
        n = n_val
        if prec is None:
            return run_dec_int_loop(d, n, op_kind, loops)
        with decimal.localcontext() as ctx:
            ctx.prec = prec
            return run_dec_int_loop(d, n, op_kind, loops)
    return bench


if __name__ == "__main__":
    runner = pyperf.Runner()

    small_a = "3.25"
    small_b = "42"
    prec28_a = "3.141592653589793238462643383"
    prec28_b = "2.718281828459045235360287471"
    prec100_a = "3." + "1415926535" * 10
    prec100_b = "2." + "7182818284" * 10

    int_31 = 1_234_567_891
    int_62 = (1 << 62) - 12345
    int_84 = 10**25 + 7

    cases = [
        ("dec_add_dec", make_dec_dec_op(small_a, small_b, "add")),
        ("dec_sub_dec", make_dec_dec_op(small_a, small_b, "sub")),
        ("dec_mul_dec", make_dec_dec_op(small_a, small_b, "mul")),
        ("dec_truediv_dec", make_dec_dec_op(small_a, small_b, "truediv")),
        ("dec_floordiv_dec", make_dec_dec_op(small_b, small_a, "floordiv")),
        ("dec_mod_dec", make_dec_dec_op(small_b, small_a, "mod")),
        ("dec_dec_mixed4_small", make_dec_dec_op(small_a, small_b, "mixed4")),
        ("dec_dec_mixed4_prec28", make_dec_dec_op(prec28_a, prec28_b, "mixed4")),
        ("dec_dec_mixed4_prec100", make_dec_dec_op(prec100_a, prec100_b, "mixed4", prec=100)),
        ("dec_add_int31", make_dec_int_op(small_a, int_31, "add")),
        ("int31_sub_dec", make_dec_int_op(small_a, int_31, "rsub")),
        ("dec_mul_int31", make_dec_int_op(small_a, int_31, "mul")),
        ("int31_truediv_dec", make_dec_int_op(small_a, int_31, "rtruediv")),
        ("dec_floordiv_int31", make_dec_int_op("1000000000000.5", int_31, "floordiv")),
        ("dec_mod_int31", make_dec_int_op("1000000000000.5", int_31, "mod")),
        ("dec_int31_mixed4_small", make_dec_int_op(small_a, int_31, "mixed4")),
        ("dec_int62_mixed4_small", make_dec_int_op(small_a, int_62, "mixed4")),
        ("dec_int84_overflow_mixed4", make_dec_int_op(small_a, int_84, "mixed4")),
        ("dec_int62_mixed4_prec28", make_dec_int_op(prec28_a, int_62, "mixed4")),
    ]

    for name, fn in cases:
        runner.bench_time_func(name, fn)

\
if ((result = dec_alloc(state)) == NULL) { \
Expand Down
Loading