Skip to content

Commit 715962c

Browse files
authored
perf: optimize factorial function performance (#19575)
## Which issue does this PR close? <!-- We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123. --> - Closes #. ## Rationale for this change benchmark ``` factorial_array time: [778.63 ns 783.03 ns 787.52 ns] change: [−90.314% −90.211% −90.055%] (p = 0.00 < 0.05) Performance has improved. factorial_scalar time: [317.32 ns 319.36 ns 321.41 ns] change: [−28.219% −27.508% −26.683%] (p = 0.00 < 0.05) Performance has improved. ``` <!-- Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed. Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes. --> ## What changes are included in this PR? 1. factorial implementation from using loop to looking up precomputed values. 2. using the `try_unary` kernel function on `PrimitiveArray`. (However, since this isn’t `unary` function, it does not get vectorized execution) and add benchmark <!-- There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR. --> ## Are these changes tested? Yes. <!-- We typically require tests for all PRs in order to: 1. Prevent the code from being accidentally broken by subsequent changes 2. Serve as another way to document the expected behavior of the code If tests are not included in your PR, please explain why (for example, are they covered by existing tests)? --> ## Are there any user-facing changes? No. <!-- If there are user-facing changes then we may require documentation to be updated before approving the PR. --> <!-- If there are any breaking changes to public APIs, please add the `api change` label. -->
1 parent a295698 commit 715962c

File tree

4 files changed

+124
-28
lines changed

4 files changed

+124
-28
lines changed

datafusion/functions/Cargo.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,3 +299,8 @@ required-features = ["unicode_expressions"]
299299
harness = false
300300
name = "left"
301301
required-features = ["unicode_expressions"]
302+
303+
[[bench]]
304+
harness = false
305+
name = "factorial"
306+
required-features = ["math_expressions"]
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
extern crate criterion;
19+
20+
use arrow::array::Int64Array;
21+
use arrow::datatypes::{DataType, Field};
22+
use criterion::{Criterion, criterion_group, criterion_main};
23+
use datafusion_common::ScalarValue;
24+
use datafusion_common::config::ConfigOptions;
25+
use datafusion_expr::ScalarFunctionArgs;
26+
use datafusion_expr_common::columnar_value::ColumnarValue;
27+
use datafusion_functions::math::factorial;
28+
use std::hint::black_box;
29+
use std::sync::Arc;
30+
31+
fn criterion_benchmark(c: &mut Criterion) {
32+
let factorial = factorial();
33+
let config_options = Arc::new(ConfigOptions::default());
34+
35+
let arr_args = vec![ColumnarValue::Array(Arc::new(Int64Array::from_iter(
36+
(0..1024).map(|i| Some(i % 21)),
37+
)))];
38+
c.bench_function(&format!("{}_array", factorial.name()), |b| {
39+
b.iter(|| {
40+
let args_cloned = arr_args.clone();
41+
black_box(factorial.invoke_with_args(ScalarFunctionArgs {
42+
args: args_cloned,
43+
arg_fields: vec![Field::new("a", DataType::Utf8, true).into()],
44+
number_rows: arr_args.len(),
45+
return_field: Field::new("f", DataType::Utf8, true).into(),
46+
config_options: Arc::clone(&config_options),
47+
}))
48+
})
49+
});
50+
51+
let scalar_args = vec![ColumnarValue::Scalar(ScalarValue::Int64(Some(20)))];
52+
c.bench_function(&format!("{}_scalar", factorial.name()), |b| {
53+
b.iter(|| {
54+
let args_cloned = scalar_args.clone();
55+
black_box(factorial.invoke_with_args(ScalarFunctionArgs {
56+
args: args_cloned,
57+
arg_fields: vec![Field::new("a", DataType::Utf8, true).into()],
58+
number_rows: 1,
59+
return_field: Field::new("f", DataType::Utf8, true).into(),
60+
config_options: Arc::clone(&config_options),
61+
}))
62+
})
63+
});
64+
}
65+
66+
criterion_group!(benches, criterion_benchmark);
67+
criterion_main!(benches);

datafusion/functions/src/math/factorial.rs

Lines changed: 51 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -15,18 +15,15 @@
1515
// specific language governing permissions and limitations
1616
// under the License.
1717

18-
use arrow::{
19-
array::{ArrayRef, Int64Array},
20-
error::ArrowError,
21-
};
18+
use arrow::array::{ArrayRef, AsArray, Int64Array};
2219
use std::any::Any;
2320
use std::sync::Arc;
2421

25-
use arrow::datatypes::DataType;
2622
use arrow::datatypes::DataType::Int64;
23+
use arrow::datatypes::{DataType, Int64Type};
2724

2825
use crate::utils::make_scalar_function;
29-
use datafusion_common::{Result, arrow_datafusion_err, exec_err};
26+
use datafusion_common::{Result, exec_err};
3027
use datafusion_expr::{
3128
ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
3229
Volatility,
@@ -92,50 +89,77 @@ impl ScalarUDFImpl for FactorialFunc {
9289
}
9390
}
9491

92+
const FACTORIALS: [i64; 21] = [
93+
1,
94+
1,
95+
2,
96+
6,
97+
24,
98+
120,
99+
720,
100+
5040,
101+
40320,
102+
362880,
103+
3628800,
104+
39916800,
105+
479001600,
106+
6227020800,
107+
87178291200,
108+
1307674368000,
109+
20922789888000,
110+
355687428096000,
111+
6402373705728000,
112+
121645100408832000,
113+
2432902008176640000,
114+
]; // if return type changes, this constant needs to be updated accordingly
115+
95116
/// Factorial SQL function
96117
fn factorial(args: &[ArrayRef]) -> Result<ArrayRef> {
97118
match args[0].data_type() {
98119
Int64 => {
99-
let arg = downcast_named_arg!((&args[0]), "value", Int64Array);
100-
Ok(arg
101-
.iter()
102-
.map(|a| match a {
103-
Some(a) => (2..=a)
104-
.try_fold(1i64, i64::checked_mul)
105-
.ok_or_else(|| {
106-
arrow_datafusion_err!(ArrowError::ComputeError(format!(
107-
"Overflow happened on FACTORIAL({a})"
108-
)))
109-
})
110-
.map(Some),
111-
_ => Ok(None),
112-
})
113-
.collect::<Result<Int64Array>>()
114-
.map(Arc::new)? as ArrayRef)
120+
let result: Int64Array =
121+
args[0].as_primitive::<Int64Type>().try_unary(|a| {
122+
if a < 0 {
123+
Ok(1)
124+
} else if a < FACTORIALS.len() as i64 {
125+
Ok(FACTORIALS[a as usize])
126+
} else {
127+
exec_err!("Overflow happened on FACTORIAL({a})")
128+
}
129+
})?;
130+
Ok(Arc::new(result) as ArrayRef)
115131
}
116132
other => exec_err!("Unsupported data type {other:?} for function factorial."),
117133
}
118134
}
119135

120136
#[cfg(test)]
121137
mod test {
122-
123-
use datafusion_common::cast::as_int64_array;
124-
125138
use super::*;
139+
use datafusion_common::cast::as_int64_array;
126140

127141
#[test]
128142
fn test_factorial_i64() {
129143
let args: Vec<ArrayRef> = vec![
130-
Arc::new(Int64Array::from(vec![0, 1, 2, 4])), // input
144+
Arc::new(Int64Array::from(vec![0, 1, 2, 4, 20, -1])), // input
131145
];
132146

133147
let result = factorial(&args).expect("failed to initialize function factorial");
134148
let ints =
135149
as_int64_array(&result).expect("failed to initialize function factorial");
136150

137-
let expected = Int64Array::from(vec![1, 1, 2, 24]);
151+
let expected = Int64Array::from(vec![1, 1, 2, 24, 2432902008176640000, 1]);
138152

139153
assert_eq!(ints, &expected);
140154
}
155+
156+
#[test]
157+
fn test_overflow() {
158+
let args: Vec<ArrayRef> = vec![
159+
Arc::new(Int64Array::from(vec![21])), // input
160+
];
161+
162+
let result = factorial(&args);
163+
assert!(result.is_err());
164+
}
141165
}

datafusion/sqllogictest/test_files/math.slt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -795,7 +795,7 @@ select
795795
39 Decimal128(2, 1)
796796

797797
# factorial overflow
798-
query error DataFusion error: Arrow error: Compute error: Overflow happened on FACTORIAL\(350943270\)
798+
query error DataFusion error: Execution error: Overflow happened on FACTORIAL\(350943270\)
799799
select FACTORIAL(350943270);
800800

801801
statement ok

0 commit comments

Comments
 (0)