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

Avoid temporary Decimal allocation for int64 operands in _decimal arithmetic #162777

Backlog

Description

@josh-hurst

In Modules/_decimal/_decimal.c, the six binary arithmetic slots (+, -, *, /, //, %) currently allocate a temporary Python Decimal object when one operand is an int.

For exact int operands that fit in a signed 64-bit integer, converting the integer directly into a stack mpd_t via mpd_qset_i64_exact avoids the temporary allocation while preserving existing operand order, context flags, traps, and fallback behavior for larger integers and subclasses.

Related context: #144650.

Found and prepared via an AI optimization pipeline I run; I reviewed the patch and tests locally and have a focused PR ready.

Linked PRs

Activity

  1. added
    type-feature
    performance
    extension-modules
    on Nov 28, 2026
  2. added
    pending
    on Nov 28, 2026
  3. picnixz commented on Nov 28, 2026

    @picnixz
    Member

    As in your other issue, please share benchmarks, use PGO/LTO builds, and avoid creating a PR until this has been acknowledge.

  4. josh-hurst commented on Nov 28, 2026

    @josh-hurst
    Author

    Here are the PGO+LTO benchmark results, including decimal_pi and decimal_factorial from python/pyperformance#491 (as @skirpichev asked on the closed PR) and the standalone microbenchmark script. I'll wait for feedback here before reopening a PR.

    Build & environment

    • Base commit: d88a6b9c3e
    • Machine: Apple M4 Pro, macOS 27.0.1 (arm64), Apple Clang 21.0.0, system libmpdec 4.0.1
    • Configure (identical for both builds, deterministic PGO task):
      PROFILE_TASK="-m test --pgo --randseed 4109" \
      ./configure --enable-optimizations --with-lto --with-system-libmpdec --with-ensurepip=no
    • Verified decimal.Decimal is _decimal.Decimal on both binaries, PYTHONHASHSEED=1, default pyperf settings (-p 20 -w 1 -n 3), interleaved base / patched.

    1. decimal_pi, decimal_factorial (pyperformance#491), and telco

    +-------------------+---------+-----------------------+
    | Benchmark         | base    | patched               |
    +===================+=========+=======================+
    | decimal_pi        | 148 ms  | 136 ms: 1.09x faster  |
    +-------------------+---------+-----------------------+
    | decimal_factorial | 102 ms  | 94.9 ms: 1.08x faster |
    +-------------------+---------+-----------------------+
    | telco             | 2.83 ms | 2.74 ms: 1.03x faster |
    +-------------------+---------+-----------------------+
    | Geometric mean    | (ref)   | 1.07x faster          |
    +-------------------+---------+-----------------------+
    

    (decimal_pi runs na + 8 and da + 32 inside its main loop, and decimal_factorial multiplies Decimal leaves with int base cases.)

    2. Mixed Decimal / int microbenchmark

    +-----------------------------+---------+-----------------------+
    | Benchmark                   | base    | patched               |
    +=============================+=========+=======================+
    | decimal_int_mixed_4ops      | 263 ns  | 205 ns: 1.29x faster  |
    +-----------------------------+---------+-----------------------+
    | decimal_add_int             | 61.5 ns | 47.3 ns: 1.30x faster |
    +-----------------------------+---------+-----------------------+
    | int_sub_decimal             | 66.9 ns | 52.3 ns: 1.28x faster |
    +-----------------------------+---------+-----------------------+
    | decimal_mul_int             | 55.8 ns | 40.0 ns: 1.39x faster |
    +-----------------------------+---------+-----------------------+
    | int_truediv_decimal         | 81.4 ns | 67.3 ns: 1.21x faster |
    +-----------------------------+---------+-----------------------+
    | decimal_add_decimal_control | 38.8 ns | 39.6 ns: 1.02x slower |
    +-----------------------------+---------+-----------------------+
    | Geometric mean              | (ref)   | 1.23x faster          |
    +-----------------------------+---------+-----------------------+
    

    Note the small +0.8 ns (1.02x) cost on decimal_add_decimal_control from checking PyLong_CheckExact before CONVERT_BINOP. If this approach looks worthwhile, checking PyDec_Check(self) && PyDec_Check(other) first (or only taking the PyLong_CheckExact branch when one operand is not already a Decimal) should avoid that branch on Decimal op Decimal.

    Microbenchmark script (bm_decimal_int_micro.py)
    import decimal
    import pyperf
    
    
    def bench_mixed_4ops(loops):
        d = decimal.Decimal("3.25")
        t0 = pyperf.perf_counter()
        for _ in range(loops):
            d + 42
            42 - d
            d * 42
            42 / d
        return pyperf.perf_counter() - t0
    
    
    def bench_add_int(loops):
        d = decimal.Decimal("3.25")
        t0 = pyperf.perf_counter()
        for _ in range(loops):
            d + 42
        return pyperf.perf_counter() - t0
    
    
    def bench_int_sub_dec(loops):
        d = decimal.Decimal("3.25")
        t0 = pyperf.perf_counter()
        for _ in range(loops):
            42 - d
        return pyperf.perf_counter() - t0
    
    
    def bench_mul_int(loops):
        d = decimal.Decimal("3.25")
        t0 = pyperf.perf_counter()
        for _ in range(loops):
            d * 42
        return pyperf.perf_counter() - t0
    
    
    def bench_int_truediv_dec(loops):
        d = decimal.Decimal("3.25")
        t0 = pyperf.perf_counter()
        for _ in range(loops):
            42 / d
        return pyperf.perf_counter() - t0
    
    
    def bench_dec_add_dec_control(loops):
        a = decimal.Decimal("3.25")
        b = decimal.Decimal("42")
        t0 = pyperf.perf_counter()
        for _ in range(loops):
            a + b
        return pyperf.perf_counter() - t0
    
    
    if __name__ == "__main__":
        runner = pyperf.Runner()
        runner.bench_time_func("decimal_int_mixed_4ops", bench_mixed_4ops)
        runner.bench_time_func("decimal_add_int", bench_add_int)
        runner.bench_time_func("int_sub_decimal", bench_int_sub_dec)
        runner.bench_time_func("decimal_mul_int", bench_mul_int)
        runner.bench_time_func("int_truediv_decimal", bench_int_truediv_dec)
        runner.bench_time_func("decimal_add_decimal_control", bench_dec_add_dec_control)
  5. picnixz commented on Nov 28, 2026

    @picnixz
    Member

    Instead of "42", can you use larger integers? 42 is a small integer so there might other factors of why it's faster. What about 31-bit integres for instance? or mixed arithmetic with larger values in general

  6. josh-hurst commented on Nov 28, 2026

    @josh-hurst
    Author

    Sure, I re-ran it with 1_234_567_891 and (1 << 62) - 12345. The second one is labeled int63 in the table, which is a bad name since it's really 62 bits, but it's near the top of the int64 range and that's what I was after. I also threw in 10**25 + 7 and 10**60 + 7, which don't fit in int64 at all. Same PGO+LTO build and pyperf settings as last time.

    +-----------------------------------+---------+-----------------------+
    | Benchmark                         | base    | patched               |
    +===================================+=========+=======================+
    | add_small_dec_int31               | 61.7 ns | 46.7 ns: 1.32x faster |
    +-----------------------------------+---------+-----------------------+
    | add_small_dec_int63               | 62.7 ns | 46.4 ns: 1.35x faster |
    +-----------------------------------+---------+-----------------------+
    | add_small_dec_int84_overflow      | 80.2 ns | 79.0 ns: 1.02x faster |
    +-----------------------------------+---------+-----------------------+
    | mixed4_small_dec_int31            | 271 ns  | 203 ns: 1.34x faster  |
    +-----------------------------------+---------+-----------------------+
    | mixed4_small_dec_int63            | 266 ns  | 198 ns: 1.34x faster  |
    +-----------------------------------+---------+-----------------------+
    | mixed4_small_dec_int200_overflow  | 700 ns  | 692 ns: 1.01x faster  |
    +-----------------------------------+---------+-----------------------+
    | mixed4_prec28_dec_int31           | 350 ns  | 289 ns: 1.21x faster  |
    +-----------------------------------+---------+-----------------------+
    | mixed4_prec28_dec_int63           | 346 ns  | 286 ns: 1.21x faster  |
    +-----------------------------------+---------+-----------------------+
    | mixed4_prec100_dec_int31          | 654 ns  | 596 ns: 1.10x faster  |
    +-----------------------------------+---------+-----------------------+
    | mixed4_prec100_dec_int63          | 651 ns  | 598 ns: 1.09x faster  |
    +-----------------------------------+---------+-----------------------+
    | mixed4_prec100_dec_int84_overflow | 768 ns  | 781 ns: 1.02x slower  |
    +-----------------------------------+---------+-----------------------+
    | Geometric mean                    | (ref)   | 1.14x faster          |
    +-----------------------------------+---------+-----------------------+
    
    Benchmark hidden because not significant (2): mixed4_small_dec_int84_overflow, mixed4_prec28_dec_int84_overflow
    

    So it wasn't the small int cache. The 31 and 62 bit values get pretty much the same speedup 42 did. It drops off as the Decimal side gets bigger, since at 100 digits the actual arithmetic is most of the cost. Anything past int64 goes through the old fallback, so there's nothing to gain there. I'd guess the one 1.02x slower is noise, but I haven't looked closely.

    mixed4 is just d + n, n - d, d * n, n / d in a loop. Script's below if you want to run it yourself.

    bm_decimal_int_sizes.py
    import decimal
    import pyperf
    
    
    def make_mixed_bench(d_str, n_val, prec=None):
        def bench(loops):
            d = decimal.Decimal(d_str)
            n = n_val
            if prec is None:
                t0 = pyperf.perf_counter()
                for _ in range(loops):
                    d + n
                    n - d
                    d * n
                    n / d
                return pyperf.perf_counter() - t0
            with decimal.localcontext() as ctx:
                ctx.prec = prec
                t0 = pyperf.perf_counter()
                for _ in range(loops):
                    d + n
                    n - d
                    d * n
                    n / d
                return pyperf.perf_counter() - t0
        return bench
    
    
    def make_add_bench(d_str, n_val):
        def bench(loops):
            d = decimal.Decimal(d_str)
            n = n_val
            t0 = pyperf.perf_counter()
            for _ in range(loops):
                d + n
            return pyperf.perf_counter() - t0
        return bench
    
    
    if __name__ == "__main__":
        runner = pyperf.Runner()
    
        small_d = "3.25"
        prec28_d = "3.141592653589793238462643383"
        prec100_d = "3." + "1415926535" * 10
    
        int_31 = 1_234_567_891
        int_63 = (1 << 62) - 12345
        int_84 = 10**25 + 7
        int_200 = 10**60 + 7
    
        cases = [
            ("add_small_dec_int31", make_add_bench(small_d, int_31)),
            ("add_small_dec_int63", make_add_bench(small_d, int_63)),
            ("add_small_dec_int84_overflow", make_add_bench(small_d, int_84)),
            ("mixed4_small_dec_int31", make_mixed_bench(small_d, int_31)),
            ("mixed4_small_dec_int63", make_mixed_bench(small_d, int_63)),
            ("mixed4_small_dec_int84_overflow", make_mixed_bench(small_d, int_84)),
            ("mixed4_small_dec_int200_overflow", make_mixed_bench(small_d, int_200)),
            ("mixed4_prec28_dec_int31", make_mixed_bench(prec28_d, int_31)),
            ("mixed4_prec28_dec_int63", make_mixed_bench(prec28_d, int_63)),
            ("mixed4_prec28_dec_int84_overflow", make_mixed_bench(prec28_d, int_84)),
            ("mixed4_prec100_dec_int31", make_mixed_bench(prec100_d, int_31, prec=100)),
            ("mixed4_prec100_dec_int63", make_mixed_bench(prec100_d, int_63, prec=100)),
            ("mixed4_prec100_dec_int84_overflow", make_mixed_bench(prec100_d, int_84, prec=100)),
        ]
    
        for name, fn in cases:
            runner.bench_time_func(name, fn)
  7. removed
    pending
    on Nov 28, 2026
  8. picnixz commented on Nov 28, 2026

    @picnixz
    Member

    This seems a good performance boost but I wonder whether we are not complicating the code too much. WDYT @skirpichev @eendebakpt?

  9. skirpichev commented on Nov 28, 2026

    @skirpichev
    Member

    This is something I was thinking before. Similar optimizations used in the gmpy2 or python-gmp packages. (Though, I was less interested in this. It adds a new optimization, while #144650 is about regression, coming from using heap types.)

    I reopened pr, it does make sense.

  10. added a commit that references this issue on Nov 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    extension-modulesperformancetype-feature

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions