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

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


The following commit(s) were added to refs/heads/main by this push:
     new 275adb2c0c perf(arrow-arith): divide integers by a scalar with a 
precomputed divisor (#12076)
275adb2c0c is described below

commit 275adb2c0cf3cd2cccf386c0591126a56ada7f1f
Author: Matt Butrovich <[email protected]>
AuthorDate: Thu Nov 12 22:29:59 2026 +0000

    perf(arrow-arith): divide integers by a scalar with a precomputed divisor 
(#12076)
    
    # Which issue does this PR close?
    
    - Part of #11421.
    
    # Rationale for this change
    
    Integer `/` and `%` by a scalar run a hardware divide for every value.
    This is the first kernel to use the precomputed divisors from #11467.
    
    # What changes are included in this PR?
    
    - `div` and `rem` of an `Int32`, `Int64`, `UInt32` or `UInt64` array by
    a scalar build a divisor once. An array that is at most half null
    divides every slot with `unary`, and one that is more than half null
    divides only its valid values with `try_unary`.
    - A null scalar, a divisor of 0, and a signed `/` by -1 take the
    existing kernel, so results and errors don't change.
    - On the `unary` path, null slots of the result hold the quotient or
    remainder of the input's null slot instead of zero, as they already do
    for `add_wrapping`.
    - 59e17d2af9 adds cases to the `integer_division` benchmark, so the
    benchmark bot can compare against it: division by 7, which reaches the
    divisor variants 13 and 16 don't, and arrays with half and nine tenths
    of the values null, where `main` divides only the valid values.
    
    # Are these changes tested?
    
    `test_div_rem_by_scalar_integer` in `arrow-arith/src/numeric.rs`.
    
    <img width="1600" height="3876" alt="integer-div-rem-bot"
    
src="https://github.com/user-attachments/assets/0d937669-7de4-4b5f-9db6-fc43bbf87e22";
    />
    
    Bot runs against 59e17d2af9:
    
[Neoverse-V2](https://github.com/apache/arrow-rs/pull/12076#issuecomment-6640561058),
    [Xeon
    
8581C](https://github.com/apache/arrow-rs/pull/12076#issuecomment-6640574037),
    and [Xeon 8581C with `-C
    
target-cpu=x86-64-v3`](https://github.com/apache/arrow-rs/pull/12076#issuecomment-6640577854),
    which Comet's x86 release builds use, with `UInt32` from later runs
    after its threshold changed
    
([Neoverse-V2](https://github.com/apache/arrow-rs/pull/12076#issuecomment-6640872770),
    [Xeon
    
8581C](https://github.com/apache/arrow-rs/pull/12076#issuecomment-6640876397),
    
[`x86-64-v3`](https://github.com/apache/arrow-rs/pull/12076#issuecomment-6640897790)).
    Every case is faster except `UInt32` `%` with nine tenths of the values
    null at `x86-64-v3`, at 0.95x.
    
    The gain is smallest above the null-count threshold, where the kernel
    visits only the valid values as `main` does: 0.95x to 1.7x on x86. The
    `Int32` `half_nulls` array has 4099 nulls out of 8192 and takes that
    path. The 64-bit ones have 4041 and don't, and `UInt32` stays on `unary`
    up to three quarters null.
    
    The kernel has two paths because `unary` costs the same at any null
    count, while `main` divides only the valid values and gets cheaper as
    nulls increase. With enough nulls, dividing every slot is slower than
    `main`, and the crossover depends on the type and the machine. Runs that
    measured both paths on every array with nulls set the thresholds
    
([Neoverse-V2](https://github.com/apache/arrow-rs/pull/12076#issuecomment-6639839111),
    [Xeon
    
8581C](https://github.com/apache/arrow-rs/pull/12076#issuecomment-6639832179),
    
[`x86-64-v3`](https://github.com/apache/arrow-rs/pull/12076#issuecomment-6639833808)).
    
    <details><summary>Times in us per 8192 values, as <code>main</code> /
    <code>unary</code> / valid values only</summary>
    
    | Runner | Case | Half null | Nine tenths null |
    |---|---|---|---|
    | Neoverse-V2 | `Int32` `/ 13` | 15.4 / 2.2 / 4.9 | 3.5 / 2.2 / 1.29 |
    | Neoverse-V2 | `Int64` `/ 13` | 26.9 / 6.1 / 6.0 | 6.1 / 6.1 / 1.67 |
    | Xeon 8581C | `Int32` `/ 13` | 6.5 / 5.3 / 5.1 | 1.61 / 5.4 / 1.50 |
    | Xeon 8581C | `UInt32` `/ 13` | 6.4 / 1.56 / 6.2 | 1.59 / 1.51 / 1.67 |
    | Xeon 8581C | `UInt32` `% 13` | 6.5 / 2.9 / 7.1 | 1.62 / 2.9 / 1.82 |
    | Xeon 8581C | `Int64` `/ 13` | 11.2 / 9.3 / 6.1 | 3.0 / 8.9 / 2.8 |
    | `x86-64-v3` | `Int32` `/ 13` | 7.9 / 1.63 / 4.7 | 1.98 / 1.54 / 1.59 |
    | `x86-64-v3` | `Int64` `% 13` | 13.8 / 10.5 / 5.9 | 3.7 / 10.6 / 3.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/integer_division.rs |  34 +++--
 arrow-arith/src/numeric.rs              | 231 +++++++++++++++++++++++++++++++-
 2 files changed, 254 insertions(+), 11 deletions(-)

diff --git a/arrow-arith/benches/integer_division.rs 
b/arrow-arith/benches/integer_division.rs
index 0479de31f6..188c141812 100644
--- a/arrow-arith/benches/integer_division.rs
+++ b/arrow-arith/benches/integer_division.rs
@@ -24,24 +24,40 @@ where
 {
     let mut rng = StdRng::seed_from_u64(42);
     let array = PrimitiveArray::<T>::from_iter_values((0..SIZE).map(|_| 
rng.random()));
-    // A fifth of the values null, at random positions
-    let nulls = NullBuffer::from_iter((0..SIZE).map(|_| rng.random_ratio(4, 
5)));
-    let with_nulls = PrimitiveArray::<T>::new(array.values().clone(), 
Some(nulls));
+    // A fifth, half, and nine tenths of the values null, at random positions. 
Visiting only the
+    // valid values does less work as the share of nulls grows
+    let with_nulls: Vec<_> = [
+        ("mixed_nulls", 4, 5),
+        ("half_nulls", 1, 2),
+        ("mostly_nulls", 1, 10),
+    ]
+    .into_iter()
+    .map(|(name, valid, of)| {
+        let nulls = NullBuffer::from_iter((0..SIZE).map(|_| 
rng.random_ratio(valid, of)));
+        (
+            name,
+            PrimitiveArray::<T>::new(array.values().clone(), Some(nulls)),
+        )
+    })
+    .collect();
     let mut group = c.benchmark_group(format!("integer_division_{name}"));
     group.throughput(Throughput::Elements(SIZE as u64));
     for (op, kernel) in [("div", div as Kernel), ("rem", rem)] {
-        // 16 is a power of two, which a precomputed divisor can replace with 
a shift or mask
-        for d in [13, 16] {
+        // A precomputed divisor picks a variant from the divisor: for 
unsigned types 7 needs a
+        // multiplier wider than N bits and 13 doesn't, and 16 is a power of 
two, which a shift
+        // or mask replaces
+        for d in [7, 13, 16] {
             let divisor = 
PrimitiveArray::<T>::new_scalar(T::Native::usize_as(d));
             group.bench_function(format!("{op}_{d}/no_nulls"), |b| {
                 b.iter(|| black_box(kernel(black_box(&array), 
black_box(&divisor)).unwrap()))
             });
         }
-        // `try_unary` visits only the valid values when the array has nulls
         let divisor = PrimitiveArray::<T>::new_scalar(T::Native::usize_as(13));
-        group.bench_function(format!("{op}_13/mixed_nulls"), |b| {
-            b.iter(|| black_box(kernel(black_box(&with_nulls), 
black_box(&divisor)).unwrap()))
-        });
+        for (nulls, array) in &with_nulls {
+            group.bench_function(format!("{op}_13/{nulls}"), |b| {
+                b.iter(|| black_box(kernel(black_box(array), 
black_box(&divisor)).unwrap()))
+            });
+        }
     }
     // A small array, where building a divisor is a larger share of the work. 
On fewer values,
     // the fixed cost of each call is far larger than building a divisor for 
these types.
diff --git a/arrow-arith/src/numeric.rs b/arrow-arith/src/numeric.rs
index c69ef0afe1..e0858f426c 100644
--- a/arrow-arith/src/numeric.rs
+++ b/arrow-arith/src/numeric.rs
@@ -5,6 +5,7 @@
 //! Defines numeric arithmetic kernels on [`PrimitiveArray`], such as [`add`]
 
 use std::cmp::Ordering;
+use std::convert::Infallible;
 use std::fmt::Formatter;
 use std::sync::Arc;
 
@@ -13,7 +14,10 @@ use arrow_array::temporal_conversions::{NANOSECONDS, 
SECONDS_IN_DAY};
 use arrow_array::timezone::Tz;
 use arrow_array::types::*;
 use arrow_array::*;
-use arrow_buffer::{ArrowNativeType, IntervalDayTime, IntervalMonthDayNano};
+use arrow_buffer::{
+    ArrowNativeType, DivisorI32, DivisorI64, DivisorU32, DivisorU64, 
IntervalDayTime,
+    IntervalMonthDayNano,
+};
 use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
 use num_traits::{CheckedMul, ToPrimitive};
 
@@ -222,6 +226,18 @@ fn arithmetic_op(op: Op, lhs: &dyn Datum, rhs: &dyn Datum) 
-> Result<ArrayRef, A
 
     let (l, l_scalar) = lhs.get();
     let (r, r_scalar) = rhs.get();
+    if matches!(op, Op::Div | Op::Rem) && !l_scalar && r_scalar {
+        let array = match (l.data_type(), r.data_type()) {
+            (Int32, Int32) => divisor_op_i32(op, l, r),
+            (Int64, Int64) => divisor_op_i64(op, l, r),
+            (UInt32, UInt32) => divisor_op_u32(op, l, r),
+            (UInt64, UInt64) => divisor_op_u64(op, l, r),
+            _ => None,
+        };
+        if let Some(array) = array {
+            return Ok(array);
+        }
+    }
     downcast_integer! {
         l.data_type(), r.data_type() => (integer_helper, op, l, l_scalar, r, 
r_scalar),
         (Float16, Float16) => float_op::<Float16Type>(op, l, l_scalar, r, 
r_scalar),
@@ -311,6 +327,105 @@ macro_rules! try_op_ref {
     }};
 }
 
+/// Defines `$fn`, which computes `/` or `%` of an array by a scalar with a 
precomputed divisor.
+/// It returns `None` for an op other than `/` and `%`, when the scalar is 
null, or when a value
+/// could fail to divide by it (zero, or `$fallible` for `/`), so that 
`integer_op` returns an
+/// error only for a valid value that fails. Otherwise no value can fail, and 
`unary` divides
+/// every slot, null or not, unless the array has more than `$max_nulls` 
nulls, where dividing
+/// only the valid values with `try_unary` costs less
+macro_rules! divisor_op {
+    (
+        $fn:ident,
+        $t:ty,
+        $divisor:ident,
+        |$d:ident| $fallible:expr,
+        |$len:ident| $max_nulls:expr,
+        [$($variant:ident),+]
+    ) => {
+        fn $fn(op: Op, l: &dyn Array, r: &dyn Array) -> Option<ArrayRef> {
+            let r = r.as_primitive::<$t>();
+            if r.null_count() != 0 {
+                return None;
+            }
+            let $d = r.value(0);
+            if matches!(op, Op::Div) && $fallible {
+                return None;
+            }
+            let divisor = $divisor::new($d)?;
+            let l = l.as_primitive::<$t>();
+            let $len = l.len();
+            if l.null_count() > $max_nulls {
+                // Calling the enum's `wrapping_div_rem`, which matches on the 
variant, keeps this
+                // to one `try_unary` per op
+                let Ok(array) = match op {
+                    Op::Div => l.try_unary::<_, $t, Infallible>(move |n| {
+                        Ok(divisor.wrapping_div_rem(n).0)
+                    }),
+                    Op::Rem => l.try_unary::<_, $t, Infallible>(move |n| {
+                        Ok(divisor.wrapping_div_rem(n).1)
+                    }),
+                    _ => return None,
+                };
+                return Some(Arc::new(array));
+            }
+            // Match on the variant once, outside the loop, and move it into 
the closure, so the
+            // loop doesn't branch on the variant. The `Op::Div` and `Op::Rem` 
arms after the
+            // variants cover variants that arrow-buffer may add later
+            let array: PrimitiveArray<$t> = match (op, divisor) {
+                $(
+                    (Op::Div, $divisor::$variant(d)) => l.unary(move |n| 
d.wrapping_div_rem(n).0),
+                    (Op::Rem, $divisor::$variant(d)) => l.unary(move |n| 
d.wrapping_div_rem(n).1),
+                )+
+                (Op::Div, d) => l.unary(move |n| d.wrapping_div_rem(n).0),
+                (Op::Rem, d) => l.unary(move |n| d.wrapping_div_rem(n).1),
+                _ => return None,
+            };
+            Some(Arc::new(array))
+        }
+    };
+}
+
+// `MIN / -1` overflows, but `%` by -1 doesn't, because `integer_op` computes 
`%` with
+// `mod_wrapping`.
+//
+// `unary` costs the same whatever the nulls, and `try_unary` visits only the 
valid values. On x86,
+// `unary` is slower than `integer_op`'s `try_unary` with a hardware divide 
above roughly 60% nulls
+// for `Int32` and `Int64`, so more than half null takes `try_unary`. 
`UInt32`'s `unary` loop is
+// the cheapest, and on x86 its `try_unary` costs about as much as 
`integer_op`'s, so it stays on
+// `unary` up to three quarters null. Its `%` on `unary` falls behind 
`integer_op`'s at roughly 80%
+divisor_op!(
+    divisor_op_i32,
+    Int32Type,
+    DivisorI32,
+    |d| d == -1,
+    |len| len / 2,
+    [PowerOfTwo, AddIndicator]
+);
+divisor_op!(
+    divisor_op_i64,
+    Int64Type,
+    DivisorI64,
+    |d| d == -1,
+    |len| len / 2,
+    [PowerOfTwo, AddIndicator]
+);
+divisor_op!(
+    divisor_op_u32,
+    UInt32Type,
+    DivisorU32,
+    |_d| false,
+    |len| len / 4 * 3,
+    [PowerOfTwo, Up, Down, AddIndicator]
+);
+divisor_op!(
+    divisor_op_u64,
+    UInt64Type,
+    DivisorU64,
+    |_d| false,
+    |len| len / 2,
+    [PowerOfTwo, Up, AddIndicator]
+);
+
 /// Perform an arithmetic operation on integers
 fn integer_op<T: ArrowPrimitiveType>(
     op: Op,
@@ -1168,7 +1283,7 @@ where
 mod tests {
     use super::*;
     use arrow_array::temporal_conversions::{as_date, as_datetime};
-    use arrow_buffer::{ScalarBuffer, i256};
+    use arrow_buffer::{NullBuffer, ScalarBuffer, i256};
     use chrono::{DateTime, NaiveDate};
 
     // The valid date range of NaiveDate is from January 1, -262143 to 
December 31, 262142 (Gregorian calendar).
@@ -1189,6 +1304,118 @@ mod tests {
         date.signed_duration_since(EPOCH).num_days() as i32
     }
 
+    fn assert_kernel_result<T: ArrowPrimitiveType>(
+        actual: Result<ArrayRef, ArrowError>,
+        expected: Result<Vec<Option<T::Native>>, ArrowError>,
+        context: &str,
+    ) {
+        match (actual, expected) {
+            (Ok(actual), Ok(expected)) => {
+                let actual: Vec<_> = 
actual.as_primitive::<T>().iter().collect();
+                assert_eq!(actual, expected, "{context}");
+            }
+            (Err(actual), Err(expected)) => {
+                assert_eq!(actual.to_string(), expected.to_string(), 
"{context}")
+            }
+            (actual, expected) => panic!("{context}: {actual:?} != 
{expected:?}"),
+        }
+    }
+
+    /// Checks `div` and `rem` of `values` by each of `divisors` and by a null 
divisor, against
+    /// `div_checked` and `mod_wrapping` on each valid value, as `integer_op` 
computes them.
+    /// `values` is repeated to 64 values so that the vectorized loop runs, 
and is also checked
+    /// sliced to 50 values, which leaves a remainder for the scalar loop, 
with seven in eight
+    /// values null, all null, and empty
+    fn test_div_rem_by_scalar<T: ArrowPrimitiveType>(
+        values: &[Option<T::Native>],
+        divisors: &[T::Native],
+    ) {
+        let values: PrimitiveArray<T> = 
values.iter().cycle().take(64).collect();
+        let mostly_null = NullBuffer::from_iter((0..values.len()).map(|i| i % 
8 == 0));
+        let arrays = [
+            values.slice(3, 50),
+            PrimitiveArray::new(values.values().clone(), Some(mostly_null)),
+            values.slice(0, 0),
+            PrimitiveArray::new_null(2),
+            values,
+        ];
+        for array in &arrays {
+            for &d in divisors {
+                let divisor = PrimitiveArray::<T>::new_scalar(d);
+                let expected = array
+                    .iter()
+                    .map(|v| v.map(|v| v.div_checked(d)).transpose())
+                    .collect();
+                assert_kernel_result::<T>(div(array, &divisor), expected, 
&format!("/ {d:?}"));
+                let expected = array
+                    .iter()
+                    .map(|v| {
+                        v.map(|v| match d.is_zero() {
+                            true => Err(ArrowError::DivideByZero),
+                            false => Ok(v.mod_wrapping(d)),
+                        })
+                        .transpose()
+                    })
+                    .collect();
+                assert_kernel_result::<T>(rem(array, &divisor), expected, 
&format!("% {d:?}"));
+            }
+            // A null divisor gives a null result, whatever its slot holds
+            for slot in [0, 7] {
+                let slot = vec![T::Native::usize_as(slot)].into();
+                let divisor = Scalar::new(PrimitiveArray::<T>::new(
+                    slot,
+                    Some(NullBuffer::new_null(1)),
+                ));
+                assert_eq!(div(array, &divisor).unwrap().null_count(), 
array.len());
+                assert_eq!(rem(array, &divisor).unwrap().null_count(), 
array.len());
+            }
+        }
+    }
+
+    #[test]
+    fn test_div_rem_by_scalar_integer() {
+        // 16, 13, 7, -16 and -7 reach each variant of the precomputed 
divisor. 0, and -1 for `/`, fall back
+        // to `integer_op`, which returns an error for a valid value and `Ok` 
otherwise
+        let values = [
+            Some(i32::MIN),
+            Some(i32::MIN + 1),
+            Some(-7),
+            None,
+            Some(0),
+            Some(13),
+            Some(i32::MAX),
+        ];
+        test_div_rem_by_scalar::<Int32Type>(&values, &[16, 13, 7, -16, -7, 0, 
-1]);
+        let values = [
+            Some(i64::MIN),
+            Some(i64::MIN + 1),
+            Some(-7),
+            None,
+            Some(0),
+            Some(13),
+            Some(i64::MAX),
+        ];
+        test_div_rem_by_scalar::<Int64Type>(&values, &[16, 13, 7, -16, -7, 0, 
-1]);
+        let values = [
+            Some(0),
+            Some(1),
+            None,
+            Some(13),
+            Some(u32::MAX - 1),
+            Some(u32::MAX),
+        ];
+        test_div_rem_by_scalar::<UInt32Type>(&values, &[16, 13, 7, 0]);
+        let values = [
+            Some(0),
+            Some(1),
+            None,
+            Some(13),
+            Some(u64::MAX - 1),
+            Some(u64::MAX),
+        ];
+        test_div_rem_by_scalar::<UInt64Type>(&values, &[16, 13, 7, 0]);
+    }
+
     fn test_neg_primitive<T: ArrowPrimitiveType>(
         input: &[T::Native],
         out: Result<&[T::Native], &str>,

Reply via email to