← 输入框|github.com|刷新
Skip to content

gh-162777: Avoid a temporary Decimal for arithmetic with small integers - #162778

Open
josh-hurst wants to merge 2 commits into
python:mainfrom
josh-hurst:perf/decimal-int64-stack-gh-162777
Open

josh-hurst wants to merge 2 commits into
python:mainfrom
josh-hurst:perf/decimal-int64-stack-gh-162777

Conversation

@josh-hurst

Copy link
Copy Markdown

Avoid allocating a temporary Python Decimal when an arithmetic slot receives an exact integer that fits in int64. Convert the integer exactly into a stack mpd_t (mpd_qset_i64_exact) and apply the current context to the operation. Larger integers, bool, and int subclasses keep the existing conversion.

Across five alternating AB/BA pairs on a 14-core Apple M4 Pro (macOS 27.0.1, libmpdec 4.0.1), mixed Decimal/int arithmetic sped up by 1.341x (median paired ratio); telco was unchanged within noise (0.93–1.05x across pairs).

Tested with test_decimal (750 passed / 9 skipped) under standard, --disable-gil, and --with-pydebug (-R 3:3 ref-leak clean).

Found and written by an AI optimization pipeline I run; I reviewed every line, ran the tests (including --disable-gil and --with-pydebug), and can answer for it.

@python-cla-bot

python-cla-bot Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

@skirpichev skirpichev left a comment

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.

mixed Decimal/int arithmetic sped up by 1.341x (median paired ratio)

Could you please provide benchmarks with results?

telco was unchanged within noise (0.93–1.05x across pairs).

Please run also decimal_pi and decimal_factorial benchmarks. See python/pyperformance#491.

@picnixz picnixz closed this Nov 28, 2026
@skirpichev skirpichev reopened this Nov 28, 2026
@bedevere-app bedevere-app Bot added the type-feature A feature request or enhancement label Nov 28, 2026
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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting review type-feature A feature request or enhancement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants