Skip to content

Commit 3ea21aa

Browse files
perf: Optimize trunc scalar performance (#19788)
## 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 `trunc` implementation always converts scalar inputs to arrays via `make_scalar_function`, 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 `trunc` function to process Float32/Float64 scalar inputs directly - Handle optional precision argument for scalar inputs - Add scalar benchmarks 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? Yes all sqllogictest pass ## Benchmark Results | Type | Before | After | Speedup | |------|--------|-------|---------| | f64 scalar | 256 ns | 55 ns | **4.6x** | | f32 scalar | 247 ns | 56 ns | **4.4x** | <!-- 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. --> --------- Co-authored-by: Jeffrey Vo <jeffrey.vo.australia@gmail.com>
1 parent 1ab7e41 commit 3ea21aa

File tree

2 files changed

+92
-3
lines changed

2 files changed

+92
-3
lines changed

datafusion/functions/benches/trunc.rs

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,13 @@ use std::sync::Arc;
3232

3333
fn criterion_benchmark(c: &mut Criterion) {
3434
let trunc = trunc();
35+
let config_options = Arc::new(ConfigOptions::default());
36+
3537
for size in [1024, 4096, 8192] {
3638
let f32_array = Arc::new(create_primitive_array::<Float32Type>(size, 0.2));
3739
let f32_args = vec![ColumnarValue::Array(f32_array)];
3840
let arg_fields = vec![Field::new("a", DataType::Float32, false).into()];
3941
let return_field = Field::new("f", DataType::Float32, true).into();
40-
let config_options = Arc::new(ConfigOptions::default());
4142

4243
c.bench_function(&format!("trunc f32 array: {size}"), |b| {
4344
b.iter(|| {
@@ -74,6 +75,51 @@ fn criterion_benchmark(c: &mut Criterion) {
7475
})
7576
});
7677
}
78+
79+
// Scalar benchmarks - to measure optimized performance
80+
let scalar_f64_args = vec![ColumnarValue::Scalar(
81+
datafusion_common::ScalarValue::Float64(Some(std::f64::consts::PI)),
82+
)];
83+
let scalar_arg_fields = vec![Field::new("a", DataType::Float64, false).into()];
84+
let scalar_return_field = Field::new("f", DataType::Float64, false).into();
85+
86+
c.bench_function("trunc f64 scalar", |b| {
87+
b.iter(|| {
88+
black_box(
89+
trunc
90+
.invoke_with_args(ScalarFunctionArgs {
91+
args: scalar_f64_args.clone(),
92+
arg_fields: scalar_arg_fields.clone(),
93+
number_rows: 1,
94+
return_field: Arc::clone(&scalar_return_field),
95+
config_options: Arc::clone(&config_options),
96+
})
97+
.unwrap(),
98+
)
99+
})
100+
});
101+
102+
let scalar_f32_args = vec![ColumnarValue::Scalar(
103+
datafusion_common::ScalarValue::Float32(Some(std::f32::consts::PI)),
104+
)];
105+
let scalar_f32_arg_fields = vec![Field::new("a", DataType::Float32, false).into()];
106+
let scalar_f32_return_field = Field::new("f", DataType::Float32, false).into();
107+
108+
c.bench_function("trunc f32 scalar", |b| {
109+
b.iter(|| {
110+
black_box(
111+
trunc
112+
.invoke_with_args(ScalarFunctionArgs {
113+
args: scalar_f32_args.clone(),
114+
arg_fields: scalar_f32_arg_fields.clone(),
115+
number_rows: 1,
116+
return_field: Arc::clone(&scalar_f32_return_field),
117+
config_options: Arc::clone(&config_options),
118+
})
119+
.unwrap(),
120+
)
121+
})
122+
});
77123
}
78124

79125
criterion_group!(benches, criterion_benchmark);

datafusion/functions/src/math/trunc.rs

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ use arrow::array::{ArrayRef, AsArray, PrimitiveArray};
2424
use arrow::datatypes::DataType::{Float32, Float64};
2525
use arrow::datatypes::{DataType, Float32Type, Float64Type, Int64Type};
2626
use datafusion_common::ScalarValue::Int64;
27-
use datafusion_common::{Result, exec_err};
27+
use datafusion_common::{Result, ScalarValue, exec_err};
2828
use datafusion_expr::TypeSignature::Exact;
2929
use datafusion_expr::sort_properties::{ExprProperties, SortProperties};
3030
use datafusion_expr::{
@@ -110,7 +110,50 @@ impl ScalarUDFImpl for TruncFunc {
110110
}
111111

112112
fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
113-
make_scalar_function(trunc, vec![])(&args.args)
113+
// Extract precision from second argument (default 0)
114+
let precision = match args.args.get(1) {
115+
Some(ColumnarValue::Scalar(Int64(Some(p)))) => Some(*p),
116+
Some(ColumnarValue::Scalar(Int64(None))) => None, // null precision
117+
Some(ColumnarValue::Array(_)) => {
118+
// Precision is an array - use array path
119+
return make_scalar_function(trunc, vec![])(&args.args);
120+
}
121+
None => Some(0), // default precision
122+
Some(cv) => {
123+
return exec_err!(
124+
"trunc function requires precision to be Int64, got {:?}",
125+
cv.data_type()
126+
);
127+
}
128+
};
129+
130+
// Scalar fast path using tuple matching for (value, precision)
131+
match (&args.args[0], precision) {
132+
// Null cases
133+
(ColumnarValue::Scalar(sv), _) if sv.is_null() => {
134+
ColumnarValue::Scalar(ScalarValue::Null).cast_to(args.return_type(), None)
135+
}
136+
(_, None) => {
137+
ColumnarValue::Scalar(ScalarValue::Null).cast_to(args.return_type(), None)
138+
}
139+
// Scalar cases
140+
(ColumnarValue::Scalar(ScalarValue::Float64(Some(v))), Some(p)) => Ok(
141+
ColumnarValue::Scalar(ScalarValue::Float64(Some(if p == 0 {
142+
v.trunc()
143+
} else {
144+
compute_truncate64(*v, p)
145+
}))),
146+
),
147+
(ColumnarValue::Scalar(ScalarValue::Float32(Some(v))), Some(p)) => Ok(
148+
ColumnarValue::Scalar(ScalarValue::Float32(Some(if p == 0 {
149+
v.trunc()
150+
} else {
151+
compute_truncate32(*v, p)
152+
}))),
153+
),
154+
// Array path for everything else
155+
_ => make_scalar_function(trunc, vec![])(&args.args),
156+
}
114157
}
115158

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

0 commit comments

Comments
 (0)