This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch 
gh-readonly-queue/main/pr-12080-2a007e8ef61106711ded9148d7eb95ddf3aebd33
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git

commit 00788df81b052d817e16dade9cf67f6ebd81c97a
Author: Matt Butrovich <[email protected]>
AuthorDate: Fri Nov 13 01:39:02 2026 +0000

    perf(arrow-arith): inline decimal `div` and `rem` by a scalar into 
`try_unary` (#12080)
    
    # Which issue does this PR close?
    
    - Closes #11529.
    - Part of #11421.
    
    # Rationale for this change
    
    See #11529. This PR takes the narrower option from the issue and changes
    only the `decimal_op` closures, because moving the error out of line in
    `ArrowNativeTypeOp` slowed integer division with nulls.
    
    # What changes are included in this PR?
    
    - `div` and `rem` of a decimal array by a valid scalar scale the scalar
    once. When the scaled divisor fits and is neither 0 nor -1, no value can
    fail on the divisor, so the closure has no per-value checks of it. In
    release builds for aarch64 and for x86_64 at the default target and at
    `x86-64-v3`, LLVM then inlines the closure into the loop of `try_unary`
    for `Decimal32`, `Decimal64` and `Decimal128`. The `Decimal256` closure
    is still called out of line, and `i256` division dominates its cost.
    - A null scalar, a scalar on the left, a divisor of 0 or -1, and a
    divisor that overflows when scaled take the existing code, so results
    and errors don't change.
    - `rem` builds the error for a value that overflows when scaled in a
    `#[cold]` function.
    - 98ff083356 adds `rem_rescaled` cases to the `decimal_division`
    benchmark, so the benchmark bot can compare against it. In those cases
    the divisor has a larger scale than the values, so `rem` scales each
    value by 100.
    
    # Are these changes tested?
    
    `test_decimal_div_rem_by_scalar` in `arrow-arith/src/numeric.rs`
    compares division by a scalar with division by an array that repeats it,
    which takes `try_binary`, for every decimal type.
    
    <img width="1600" height="3348" alt="decimal-scalar-div-rem-bot"
    
src="https://github.com/user-attachments/assets/de2fa178-0526-408a-8e4d-6e3c1c9f1d23";
    />
    
    Bot runs against 98ff083356, with `-C llvm-args=-align-all-functions=6
    -C llvm-args=-align-all-nofallthru-blocks=6` on both sides:
    
[Neoverse-V2](https://github.com/apache/arrow-rs/pull/12080#issuecomment-6643487371),
    [Xeon
    
8581C](https://github.com/apache/arrow-rs/pull/12080#issuecomment-6643488791),
    and [Xeon 8581C with `-C
    
target-cpu=x86-64-v3`](https://github.com/apache/arrow-rs/pull/12080#issuecomment-6643573436).
    The runs without those flags
    
([Neoverse-V2](https://github.com/apache/arrow-rs/pull/12080#issuecomment-6643458002),
    [Xeon
    
8581C](https://github.com/apache/arrow-rs/pull/12080#issuecomment-6643478135),
    
[`x86-64-v3`](https://github.com/apache/arrow-rs/pull/12080#issuecomment-6644577369))
    show the same gains to within 0.25x, except for the `div` cases whose
    values overflow when scaled.
    
    `Decimal128` and `Decimal256` `/` and `%` are 1.2x to 1.7x faster on
    every runner. `Decimal32` and `Decimal64` gain less: `%` didn't change
    on Neoverse-V2, and `Decimal64` `%` measured 0.97x to 1.00x on the Xeon.
    
    The `div` cases whose values overflow when scaled take `scaled_div`,
    which this PR doesn't change. On the Xeon, the `Decimal32` case measured
    0.79x at `x86-64-v3` without the alignment flags and 1.10x to 1.21x in
    the other runs, and the `Decimal128` case measured 0.88x to 1.03x. The
    `Decimal64` case moved from 1.63x to 1.05x with only the alignment
    changed. The loop around `scaled_div` does less work per value with this
    PR, one call instead of two, and `scaled_div` compiles to the same code
    on both sides, so I read these differences as code layout. `Decimal128`
    `/` on one value measured 0.92x in the aligned `x86-64-v3` run and 1.00x
    to 1.03x in the others.
    
    <details><summary>Times in us per 1024 values from the aligned runs, as
    <code>98ff083356</code> / this PR</summary>
    
    | Case | Neoverse-V2 | Xeon 8581C | `x86-64-v3` |
    |---|---|---|---|
    | `decimal32_scalar/div_3_digits_by_4_digits/no_nulls` | 4.30 / 3.30 |
    2.60 / 1.69 | 3.20 / 1.82 |
    | `decimal32_scalar/rem_9_digits_by_4_digits/no_nulls` | 3.60 / 3.60 |
    2.30 / 1.68 | 2.60 / 1.87 |
    | `decimal32_scalar/rem_rescaled_7_digits_by_4_digits/no_nulls` | 3.60 /
    3.60 | 2.30 / 1.70 | 2.60 / 1.85 |
    | `decimal32_scalar/div_6_digits_by_4_digits/no_nulls` | 62.7 / 59.8 |
    48.4 / 44.1 | 48.9 / 44.5 |
    | `decimal64_scalar/div_3_digits_by_4_digits/no_nulls` | 4.20 / 3.30 |
    3.00 / 2.70 | 3.40 / 2.90 |
    | `decimal64_scalar/rem_18_digits_by_4_digits/no_nulls` | 6.20 / 6.20 |
    2.70 / 2.70 | 3.00 / 3.10 |
    | `decimal64_scalar/rem_rescaled_16_digits_by_4_digits/no_nulls` | 6.20
    / 6.20 | 2.70 / 2.70 | 2.90 / 3.00 |
    | `decimal64_scalar/div_15_digits_by_4_digits/no_nulls` | 65.4 / 62.4 |
    40.5 / 38.7 | 58.1 / 53.1 |
    | `decimal128_scalar/div_10_digits_by_4_digits/no_nulls` | 8.40 / 5.80 |
    9.10 / 5.50 | 10.3 / 6.7 |
    | `decimal128_scalar/rem_10_digits_by_4_digits/no_nulls` | 7.20 / 4.40 |
    9.00 / 5.40 | 10.4 / 6.5 |
    | `decimal128_scalar/rem_rescaled_30_digits_by_4_digits/no_nulls` | 15.9
    / 13.5 | 9.80 / 5.90 | 10.8 / 7.2 |
    | `decimal128_scalar/div_34_digits_by_4_digits/no_nulls` | 115.6 / 113.7
    | 67.5 / 66.6 | 72.7 / 78.0 |
    | `decimal128_scalar/div_10_digits_by_4_digits/1_values` | 0.152 / 0.151
    | 0.117 / 0.114 | 0.134 / 0.145 |
    | `decimal256_scalar/div_30_digits_by_4_digits/no_nulls` | 40.6 / 28.1 |
    33.2 / 21.4 | 36.2 / 25.3 |
    | `decimal256_scalar/rem_30_digits_by_4_digits/no_nulls` | 40.0 / 27.9 |
    35.6 / 22.2 | 37.0 / 23.7 |
    | `decimal256_scalar/rem_rescaled_60_digits_by_4_digits/no_nulls` | 56.9
    / 44.8 | 39.3 / 23.3 | 44.9 / 28.7 |
    | `decimal256_scalar/div_72_digits_by_4_digits/no_nulls` | 199.2 / 198.9
    | 182.9 / 183.5 | 208.2 / 211.0 |
    
    </details>
    
    # Are there any significant user-facing changes?
    
    No.
    
    ## AI Disclosure
    
    I wrote this PR with help from Claude but understand and support the
    core approach, implementation, and test coverage.
---
 arrow-arith/benches/decimal_division.rs |  27 ++++--
 arrow-arith/src/numeric.rs              | 156 ++++++++++++++++++++++++++++----
 2 files changed, 161 insertions(+), 22 deletions(-)

diff --git a/arrow-arith/benches/decimal_division.rs 
b/arrow-arith/benches/decimal_division.rs
index f7bde09b18..0977f0e32c 100644
--- a/arrow-arith/benches/decimal_division.rs
+++ b/arrow-arith/benches/decimal_division.rs
@@ -57,19 +57,21 @@ fn with_random_nulls<T: DecimalType>(array: 
&PrimitiveArray<T>) -> PrimitiveArra
 }
 
 /// Benchmarks `div` and `rem` of values with scale `scale` by a scalar, for 
each pair of value
-/// and divisor digit counts in `div_cases` and `rem_cases`, and `div` of the 
first `div` case
-/// on arrays of each length in `small_lens`
+/// and divisor digit counts in `div_cases`, `rem_cases` and 
`rem_rescaled_cases`, and `div` of
+/// the first `div` case on arrays of each length in `small_lens`
 ///
 /// For `div` the divisor has scale 2, so `div` scales the values by 10^6. The 
last `div` case
 /// overflows when scaled, which `div` handles one digit at a time. For `rem` 
the divisor has
 /// scale `scale`, because `rem` scales the divisor to the larger scale, which 
would change its
-/// digit count.
+/// digit count. For `rem_rescaled` the divisor has scale `scale + 2`, so 
`rem` scales the values
+/// by 100.
 fn benchmark_scalar<T: DecimalType>(
     c: &mut Criterion,
     name: &str,
     scale: i8,
     div_cases: &[(u32, u32)],
     rem_cases: &[(u32, u32)],
+    rem_rescaled_cases: &[(u32, u32)],
     small_lens: &[usize],
 ) {
     let mut group = c.benchmark_group(format!("{name}_scalar"));
@@ -78,6 +80,7 @@ fn benchmark_scalar<T: DecimalType>(
     let ops = [
         ("div", div as Kernel, 2, div_cases),
         ("rem", rem as Kernel, scale, rem_cases),
+        ("rem_rescaled", rem as Kernel, scale + 2, rem_rescaled_cases),
     ];
     let mut small = None;
     for (op, kernel, divisor_scale, cases) in ops {
@@ -127,7 +130,15 @@ fn benchmark_scalar<T: DecimalType>(
 fn decimal_scalar_division(c: &mut Criterion) {
     // Values that fit after scaling and values that overflow. For each 
overflowing value, `div`
     // also builds an `ArrowError` and discards it before falling back.
-    benchmark_scalar::<Decimal32Type>(c, "decimal32", 2, &[(3, 4), (6, 4)], 
&[(9, 4)], &[128]);
+    benchmark_scalar::<Decimal32Type>(
+        c,
+        "decimal32",
+        2,
+        &[(3, 4), (6, 4)],
+        &[(9, 4)],
+        &[(7, 4)],
+        &[128],
+    );
     // A value that fits in 32 bits after scaling, a wider one, and one that 
overflows
     benchmark_scalar::<Decimal64Type>(
         c,
@@ -135,17 +146,20 @@ fn decimal_scalar_division(c: &mut Criterion) {
         2,
         &[(3, 4), (12, 4), (15, 4)],
         &[(18, 4)],
+        &[(16, 4)],
         &[128],
     );
     // A value that fits in 64 bits after scaling, a wider one, a divisor 
wider than 64 bits, and a
-    // value that overflows. `rem` doesn't scale the values, so it has no 
overflow case. Building
-    // a divisor for these types costs more, so they also run on 1 and 16 
values.
+    // value that overflows. `rem` has no overflow case, because a value that 
overflows when
+    // `rem` scales it is an error. Building a divisor for these types costs 
more, so they also
+    // run on 1 and 16 values.
     benchmark_scalar::<Decimal128Type>(
         c,
         "decimal128",
         10,
         &[(10, 4), (30, 4), (30, 21), (34, 4)],
         &[(10, 4), (30, 4), (30, 21)],
+        &[(30, 4)],
         &[1, 16, 128],
     );
     // The same cases for 128 bits
@@ -155,6 +169,7 @@ fn decimal_scalar_division(c: &mut Criterion) {
         10,
         &[(30, 4), (60, 4), (60, 40), (72, 4)],
         &[(30, 4), (60, 4), (60, 40)],
+        &[(60, 4)],
         &[1, 16, 128],
     );
 }
diff --git a/arrow-arith/src/numeric.rs b/arrow-arith/src/numeric.rs
index e0858f426c..6238a6a7ca 100644
--- a/arrow-arith/src/numeric.rs
+++ b/arrow-arith/src/numeric.rs
@@ -1073,6 +1073,37 @@ fn date_op<T: DateOp>(
     }
 }
 
+/// Returns the scalar divisor `r` scaled by `r_mul`, when `l` is an array and 
dividing any value
+/// by it can't fail. That needs `r` to be valid and the product to fit and be 
neither 0 nor -1.
+///
+/// The kernel then needs no per-value checks of the divisor, which keeps the 
closure small
+/// enough for LLVM to inline into the loop of `try_unary`. Otherwise it 
returns `None`, and the
+/// kernel takes the general path, which reports any errors.
+fn scalar_divisor<T: DecimalType>(
+    l_s: bool,
+    r: &PrimitiveArray<T>,
+    r_s: bool,
+    r_mul: T::Native,
+) -> Option<T::Native>
+where
+    T::Native: CheckedMul,
+{
+    if l_s || !r_s || r.null_count() != 0 {
+        return None;
+    }
+    let divisor = r.value(0).checked_mul(&r_mul)?;
+    let minus_one = T::Native::ONE.neg_wrapping();
+    (!divisor.is_zero() && !divisor.is_eq(minus_one)).then_some(divisor)
+}
+
+/// [`ArrowNativeTypeOp::mul_checked`] out of line, for closures that call it 
only after
+/// `checked_mul` overflows, so that building the error doesn't stop them from 
being inlined
+#[cold]
+#[inline(never)]
+fn mul_checked_cold<T: ArrowNativeTypeOp>(l: T, r: T) -> Result<T, ArrowError> 
{
+    l.mul_checked(r)
+}
+
 /// Divides `l * 10^mul_pow` by `r` a digit at a time, without forming the 
scaled numerator.
 /// Used when scaling `l` would overflow `T::Native`, which it does well 
before the quotient
 /// does.
@@ -1241,16 +1272,26 @@ where
                 ),
             };
 
-            try_op!(
-                l,
-                l_s,
-                r,
-                r_s,
-                match l.checked_mul(&l_mul) {
-                    Some(scaled) => scaled.div_checked(r.mul_checked(r_mul)?),
-                    None => scaled_div::<T>(l, r, mul_pow),
+            match scalar_divisor(l_s, r, r_s, r_mul) {
+                Some(divisor) => {
+                    let r = r.value(0);
+                    l.try_unary(|l| match l.checked_mul(&l_mul) {
+                        // `divisor` is neither 0 nor -1, so the division 
can't fail
+                        Some(scaled) => Ok(scaled.div_wrapping(divisor)),
+                        None => scaled_div::<T>(l, r, mul_pow),
+                    })?
                 }
-            )
+                None => try_op!(
+                    l,
+                    l_s,
+                    r,
+                    r_s,
+                    match l.checked_mul(&l_mul) {
+                        Some(scaled) => 
scaled.div_checked(r.mul_checked(r_mul)?),
+                        None => scaled_div::<T>(l, r, mul_pow),
+                    }
+                ),
+            }
             .with_precision_and_scale(result_precision, result_scale)?
         }
 
@@ -1265,13 +1306,20 @@ where
             let l_mul = T::Native::usize_as(10).pow_checked((result_scale - 
s1) as _)?;
             let r_mul = T::Native::usize_as(10).pow_checked((result_scale - 
s2) as _)?;
 
-            try_op!(
-                l,
-                l_s,
-                r,
-                r_s,
-                l.mul_checked(l_mul)?.mod_checked(r.mul_checked(r_mul)?)
-            )
+            match scalar_divisor(l_s, r, r_s, r_mul) {
+                // `divisor` is neither 0 nor -1, so the remainder can't fail
+                Some(divisor) => l.try_unary(|l| match l.checked_mul(&l_mul) {
+                    Some(scaled) => Ok(scaled.mod_wrapping(divisor)),
+                    None => mul_checked_cold(l, l_mul).map(|scaled| 
scaled.mod_wrapping(divisor)),
+                })?,
+                None => try_op!(
+                    l,
+                    l_s,
+                    r,
+                    r_s,
+                    l.mul_checked(l_mul)?.mod_checked(r.mul_checked(r_mul)?)
+                ),
+            }
             .with_precision_and_scale(result_precision, result_scale as i8)?
         }
     };
@@ -2084,6 +2132,82 @@ mod tests {
         }
     }
 
+    #[test]
+    fn test_decimal_div_rem_by_scalar() {
+        // `div` and `rem` by a scalar give the same results and errors as by 
an array that
+        // repeats it, which takes `try_binary`
+        fn check<T: DecimalType>() {
+            let one = T::Native::ONE;
+            let pow = T::Native::usize_as(1_000_000);
+            let (max, min) = (T::Native::MAX_TOTAL_ORDER, 
T::Native::MIN_TOTAL_ORDER);
+            let seven = T::Native::usize_as(7);
+            let values = [
+                Some(T::Native::ZERO),
+                Some(one),
+                Some(one.neg_wrapping()),
+                Some(seven.neg_wrapping()),
+                None,
+                Some(max.div_wrapping(pow)),
+                Some(max.div_wrapping(pow).add_wrapping(one)),
+                Some(min.div_wrapping(pow).sub_wrapping(one)),
+                Some(max),
+                Some(min.add_wrapping(one)),
+                Some(min),
+            ];
+            let divisors = [
+                T::Native::ZERO,
+                one,
+                one.neg_wrapping(),
+                seven,
+                seven.neg_wrapping(),
+                T::Native::usize_as(10_000),
+                max,
+                min,
+            ];
+            // Scale pairs where the multipliers of `div` and `rem` are 1, a 
power of ten, and
+            // one that overflows the divisor
+            let scales = [(2, 2), (2, 4), (4, 2), (2, -6), (0, 0)];
+            for (s1, s2) in scales {
+                let a = PrimitiveArray::<T>::from_iter(values)
+                    .with_precision_and_scale(T::MAX_PRECISION, s1)
+                    .unwrap();
+                let arrays = [
+                    a.clone(),
+                    a.slice(1, 6),
+                    a.slice(0, 0),
+                    PrimitiveArray::<T>::new_null(3)
+                        .with_precision_and_scale(T::MAX_PRECISION, s1)
+                        .unwrap(),
+                ];
+                for divisor in divisors {
+                    let repeat = |len| {
+                        PrimitiveArray::<T>::from_iter_values(vec![divisor; 
len])
+                            .with_precision_and_scale(T::MAX_PRECISION, s2)
+                            .unwrap()
+                    };
+                    let scalar = Scalar::new(repeat(1));
+                    for a in &arrays {
+                        let b = repeat(a.len());
+                        for kernel in [div, rem] {
+                            let msg = format!("{a:?} by {divisor:?} at scales 
{s1}, {s2}");
+                            match (kernel(a, &scalar), kernel(a, &b)) {
+                                (Ok(s), Ok(b)) => assert_eq!(s.to_data(), 
b.to_data(), "{msg}"),
+                                (Err(s), Err(b)) => {
+                                    assert_eq!(s.to_string(), b.to_string(), 
"{msg}")
+                                }
+                                (s, b) => panic!("{msg}: {s:?} != {b:?}"),
+                            }
+                        }
+                    }
+                }
+            }
+        }
+        check::<Decimal32Type>();
+        check::<Decimal64Type>();
+        check::<Decimal128Type>();
+        check::<Decimal256Type>();
+    }
+
     #[test]
     fn test_decimal256_same_scale_add_sub() {
         let lhs = Decimal256Array::from(vec![

Reply via email to