Skip to content

Commit d484c09

Browse files
authored
perf: Optimize floor and ceil scalar performance (#19752)
## 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. --> - Part of apache/datafusion-comet#2986 ## Rationale for this change - The current floor and ceil implementations always convert scalar inputs to arrays via `values_to_arrays()`, which introduces unnecessary overhead when processing single values. <!-- 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? - Add scalar fast path for floor and ceil - Add criterion benchmark for floor/ceil to measure performance <!-- 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? - All sqllogictest pass - Addec benchmark | Benchmark | Array Time | Scalar Time | Speedup | |---------------------|------------|-------------|---------| | floor_f64 (1024) | ~396 ns | ~147 ns | 2.7× | | ceil_f64 (1024) | ~363 ns | ~150 ns | 2.4× | | floor_f64 (4096) | ~681 ns | ~144 ns | 4.7× | | ceil_f64 (4096) | ~667 ns | ~144 ns | 4.6× | | floor_f64 (8192) | ~1,638 ns | ~144 ns | 11.4× | | ceil_f64 (8192) | ~1,634 ns | ~144 ns | 11.3× | <!-- 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 cb9ec12 commit d484c09

File tree

4 files changed

+218
-14
lines changed

4 files changed

+218
-14
lines changed

datafusion/functions/Cargo.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,3 +315,8 @@ required-features = ["unicode_expressions"]
315315
harness = false
316316
name = "factorial"
317317
required-features = ["math_expressions"]
318+
319+
[[bench]]
320+
harness = false
321+
name = "floor_ceil"
322+
required-features = ["math_expressions"]
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
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::datatypes::{DataType, Field, Float64Type};
21+
use arrow::util::bench_util::create_primitive_array;
22+
use criterion::{Criterion, SamplingMode, criterion_group, criterion_main};
23+
use datafusion_common::ScalarValue;
24+
use datafusion_common::config::ConfigOptions;
25+
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
26+
use datafusion_functions::math::{ceil, floor};
27+
use std::hint::black_box;
28+
use std::sync::Arc;
29+
use std::time::Duration;
30+
31+
fn criterion_benchmark(c: &mut Criterion) {
32+
let floor_fn = floor();
33+
let ceil_fn = ceil();
34+
let config_options = Arc::new(ConfigOptions::default());
35+
36+
for size in [1024, 4096, 8192] {
37+
let mut group = c.benchmark_group(format!("floor_ceil size={size}"));
38+
group.sampling_mode(SamplingMode::Flat);
39+
group.sample_size(10);
40+
group.measurement_time(Duration::from_secs(10));
41+
42+
// Float64 array benchmark
43+
let f64_array = Arc::new(create_primitive_array::<Float64Type>(size, 0.1));
44+
let batch_len = f64_array.len();
45+
let f64_args = vec![ColumnarValue::Array(f64_array)];
46+
47+
group.bench_function("floor_f64_array", |b| {
48+
b.iter(|| {
49+
let args_cloned = f64_args.clone();
50+
black_box(
51+
floor_fn
52+
.invoke_with_args(ScalarFunctionArgs {
53+
args: args_cloned,
54+
arg_fields: vec![
55+
Field::new("a", DataType::Float64, true).into(),
56+
],
57+
number_rows: batch_len,
58+
return_field: Field::new("f", DataType::Float64, true).into(),
59+
config_options: Arc::clone(&config_options),
60+
})
61+
.unwrap(),
62+
)
63+
})
64+
});
65+
66+
group.bench_function("ceil_f64_array", |b| {
67+
b.iter(|| {
68+
let args_cloned = f64_args.clone();
69+
black_box(
70+
ceil_fn
71+
.invoke_with_args(ScalarFunctionArgs {
72+
args: args_cloned,
73+
arg_fields: vec![
74+
Field::new("a", DataType::Float64, true).into(),
75+
],
76+
number_rows: batch_len,
77+
return_field: Field::new("f", DataType::Float64, true).into(),
78+
config_options: Arc::clone(&config_options),
79+
})
80+
.unwrap(),
81+
)
82+
})
83+
});
84+
85+
// Scalar benchmark (the optimization we added)
86+
let scalar_args = vec![ColumnarValue::Scalar(ScalarValue::Float64(Some(
87+
std::f64::consts::PI,
88+
)))];
89+
90+
group.bench_function("floor_f64_scalar", |b| {
91+
b.iter(|| {
92+
let args_cloned = scalar_args.clone();
93+
black_box(
94+
floor_fn
95+
.invoke_with_args(ScalarFunctionArgs {
96+
args: args_cloned,
97+
arg_fields: vec![
98+
Field::new("a", DataType::Float64, false).into(),
99+
],
100+
number_rows: 1,
101+
return_field: Field::new("f", DataType::Float64, false)
102+
.into(),
103+
config_options: Arc::clone(&config_options),
104+
})
105+
.unwrap(),
106+
)
107+
})
108+
});
109+
110+
group.bench_function("ceil_f64_scalar", |b| {
111+
b.iter(|| {
112+
let args_cloned = scalar_args.clone();
113+
black_box(
114+
ceil_fn
115+
.invoke_with_args(ScalarFunctionArgs {
116+
args: args_cloned,
117+
arg_fields: vec![
118+
Field::new("a", DataType::Float64, false).into(),
119+
],
120+
number_rows: 1,
121+
return_field: Field::new("f", DataType::Float64, false)
122+
.into(),
123+
config_options: Arc::clone(&config_options),
124+
})
125+
.unwrap(),
126+
)
127+
})
128+
});
129+
130+
group.finish();
131+
}
132+
}
133+
134+
criterion_group!(benches, criterion_benchmark);
135+
criterion_main!(benches);

datafusion/functions/src/math/ceil.rs

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,35 @@ impl ScalarUDFImpl for CeilFunc {
9595
}
9696

9797
fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
98-
let args = ColumnarValue::values_to_arrays(&args.args)?;
99-
let value = &args[0];
98+
let arg = &args.args[0];
99+
100+
// Scalar fast path for float types - avoid array conversion overhead entirely
101+
if let ColumnarValue::Scalar(scalar) = arg {
102+
match scalar {
103+
ScalarValue::Float64(v) => {
104+
return Ok(ColumnarValue::Scalar(ScalarValue::Float64(
105+
v.map(f64::ceil),
106+
)));
107+
}
108+
ScalarValue::Float32(v) => {
109+
return Ok(ColumnarValue::Scalar(ScalarValue::Float32(
110+
v.map(f32::ceil),
111+
)));
112+
}
113+
ScalarValue::Null => {
114+
return Ok(ColumnarValue::Scalar(ScalarValue::Float64(None)));
115+
}
116+
// For decimals: convert to array of size 1, process, then extract scalar
117+
// This ensures we don't expand the array while reusing overflow validation
118+
_ => {}
119+
}
120+
}
121+
122+
// Track if input was a scalar to convert back at the end
123+
let is_scalar = matches!(arg, ColumnarValue::Scalar(_));
124+
125+
// Array path (also handles decimal scalars converted to size-1 arrays)
126+
let value = arg.to_array(args.number_rows)?;
100127

101128
let result: ArrayRef = match value.data_type() {
102129
DataType::Float64 => Arc::new(
@@ -114,7 +141,7 @@ impl ScalarUDFImpl for CeilFunc {
114141
}
115142
DataType::Decimal32(precision, scale) => {
116143
apply_decimal_op::<Decimal32Type, _>(
117-
value,
144+
&value,
118145
*precision,
119146
*scale,
120147
self.name(),
@@ -123,7 +150,7 @@ impl ScalarUDFImpl for CeilFunc {
123150
}
124151
DataType::Decimal64(precision, scale) => {
125152
apply_decimal_op::<Decimal64Type, _>(
126-
value,
153+
&value,
127154
*precision,
128155
*scale,
129156
self.name(),
@@ -132,7 +159,7 @@ impl ScalarUDFImpl for CeilFunc {
132159
}
133160
DataType::Decimal128(precision, scale) => {
134161
apply_decimal_op::<Decimal128Type, _>(
135-
value,
162+
&value,
136163
*precision,
137164
*scale,
138165
self.name(),
@@ -141,7 +168,7 @@ impl ScalarUDFImpl for CeilFunc {
141168
}
142169
DataType::Decimal256(precision, scale) => {
143170
apply_decimal_op::<Decimal256Type, _>(
144-
value,
171+
&value,
145172
*precision,
146173
*scale,
147174
self.name(),
@@ -156,7 +183,12 @@ impl ScalarUDFImpl for CeilFunc {
156183
}
157184
};
158185

159-
Ok(ColumnarValue::Array(result))
186+
// If input was a scalar, convert result back to scalar
187+
if is_scalar {
188+
ScalarValue::try_from_array(&result, 0).map(ColumnarValue::Scalar)
189+
} else {
190+
Ok(ColumnarValue::Array(result))
191+
}
160192
}
161193

162194
fn output_ordering(&self, input: &[ExprProperties]) -> Result<SortProperties> {

datafusion/functions/src/math/floor.rs

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,35 @@ impl ScalarUDFImpl for FloorFunc {
9595
}
9696

9797
fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
98-
let args = ColumnarValue::values_to_arrays(&args.args)?;
99-
let value = &args[0];
98+
let arg = &args.args[0];
99+
100+
// Scalar fast path for float types - avoid array conversion overhead entirely
101+
if let ColumnarValue::Scalar(scalar) = arg {
102+
match scalar {
103+
ScalarValue::Float64(v) => {
104+
return Ok(ColumnarValue::Scalar(ScalarValue::Float64(
105+
v.map(f64::floor),
106+
)));
107+
}
108+
ScalarValue::Float32(v) => {
109+
return Ok(ColumnarValue::Scalar(ScalarValue::Float32(
110+
v.map(f32::floor),
111+
)));
112+
}
113+
ScalarValue::Null => {
114+
return Ok(ColumnarValue::Scalar(ScalarValue::Float64(None)));
115+
}
116+
// For decimals: convert to array of size 1, process, then extract scalar
117+
// This ensures we don't expand the array while reusing overflow validation
118+
_ => {}
119+
}
120+
}
121+
122+
// Track if input was a scalar to convert back at the end
123+
let is_scalar = matches!(arg, ColumnarValue::Scalar(_));
124+
125+
// Array path (also handles decimal scalars converted to size-1 arrays)
126+
let value = arg.to_array(args.number_rows)?;
100127

101128
let result: ArrayRef = match value.data_type() {
102129
DataType::Float64 => Arc::new(
@@ -114,7 +141,7 @@ impl ScalarUDFImpl for FloorFunc {
114141
}
115142
DataType::Decimal32(precision, scale) => {
116143
apply_decimal_op::<Decimal32Type, _>(
117-
value,
144+
&value,
118145
*precision,
119146
*scale,
120147
self.name(),
@@ -123,7 +150,7 @@ impl ScalarUDFImpl for FloorFunc {
123150
}
124151
DataType::Decimal64(precision, scale) => {
125152
apply_decimal_op::<Decimal64Type, _>(
126-
value,
153+
&value,
127154
*precision,
128155
*scale,
129156
self.name(),
@@ -132,7 +159,7 @@ impl ScalarUDFImpl for FloorFunc {
132159
}
133160
DataType::Decimal128(precision, scale) => {
134161
apply_decimal_op::<Decimal128Type, _>(
135-
value,
162+
&value,
136163
*precision,
137164
*scale,
138165
self.name(),
@@ -141,7 +168,7 @@ impl ScalarUDFImpl for FloorFunc {
141168
}
142169
DataType::Decimal256(precision, scale) => {
143170
apply_decimal_op::<Decimal256Type, _>(
144-
value,
171+
&value,
145172
*precision,
146173
*scale,
147174
self.name(),
@@ -156,7 +183,12 @@ impl ScalarUDFImpl for FloorFunc {
156183
}
157184
};
158185

159-
Ok(ColumnarValue::Array(result))
186+
// If input was a scalar, convert result back to scalar
187+
if is_scalar {
188+
ScalarValue::try_from_array(&result, 0).map(ColumnarValue::Scalar)
189+
} else {
190+
Ok(ColumnarValue::Array(result))
191+
}
160192
}
161193

162194
fn output_ordering(&self, input: &[ExprProperties]) -> Result<SortProperties> {

0 commit comments

Comments
 (0)