Skip to content

Commit c0e80ed

Browse files
authored
perf: Optimize scalar fast path of atan2 (#20336)
## 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 atan2 scalar calls were still going through array conversion in the math binary UDF macro, adding unnecessary overhead for constant folding and scalar evaluation. This PR adds a direct scalar fast path so scalar inputs no longer pay that cost <!-- 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 a scalar fast path to the binary math UDF macro (used by atan2) - Add a new atan2 benchmark | Type | Before | After | Speedup | |------|--------|-------|---------| | atan2_f32_scalar | 233.71 ns | 53.39 ns | 4.4x | | atan2_f64_scalar | 225.02 ns | 56.57 ns | 4.0x | Note: This change targets the make_math_binary_udf macro, which is currently only used by atan2, so the impact in this PR is limited to atan2 only. <!-- 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 d692df0 commit c0e80ed

File tree

3 files changed

+222
-31
lines changed

3 files changed

+222
-31
lines changed

datafusion/functions/Cargo.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,11 @@ harness = false
192192
name = "signum"
193193
required-features = ["math_expressions"]
194194

195+
[[bench]]
196+
harness = false
197+
name = "atan2"
198+
required-features = ["math_expressions"]
199+
195200
[[bench]]
196201
harness = false
197202
name = "substr_index"
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
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, Float32Type, Float64Type};
21+
use arrow::util::bench_util::create_primitive_array;
22+
use criterion::{Criterion, 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::atan2;
27+
use std::hint::black_box;
28+
use std::sync::Arc;
29+
30+
fn criterion_benchmark(c: &mut Criterion) {
31+
let atan2_fn = atan2();
32+
let config_options = Arc::new(ConfigOptions::default());
33+
34+
for size in [1024, 4096, 8192] {
35+
let y_f32 = Arc::new(create_primitive_array::<Float32Type>(size, 0.2));
36+
let x_f32 = Arc::new(create_primitive_array::<Float32Type>(size, 0.2));
37+
let f32_args = vec![ColumnarValue::Array(y_f32), ColumnarValue::Array(x_f32)];
38+
let f32_arg_fields = f32_args
39+
.iter()
40+
.enumerate()
41+
.map(|(idx, arg)| {
42+
Field::new(format!("arg_{idx}"), arg.data_type(), true).into()
43+
})
44+
.collect::<Vec<_>>();
45+
let return_field_f32 = Field::new("f", DataType::Float32, true).into();
46+
47+
c.bench_function(&format!("atan2 f32 array: {size}"), |b| {
48+
b.iter(|| {
49+
black_box(
50+
atan2_fn
51+
.invoke_with_args(ScalarFunctionArgs {
52+
args: f32_args.clone(),
53+
arg_fields: f32_arg_fields.clone(),
54+
number_rows: size,
55+
return_field: Arc::clone(&return_field_f32),
56+
config_options: Arc::clone(&config_options),
57+
})
58+
.unwrap(),
59+
)
60+
})
61+
});
62+
63+
let y_f64 = Arc::new(create_primitive_array::<Float64Type>(size, 0.2));
64+
let x_f64 = Arc::new(create_primitive_array::<Float64Type>(size, 0.2));
65+
let f64_args = vec![ColumnarValue::Array(y_f64), ColumnarValue::Array(x_f64)];
66+
let f64_arg_fields = f64_args
67+
.iter()
68+
.enumerate()
69+
.map(|(idx, arg)| {
70+
Field::new(format!("arg_{idx}"), arg.data_type(), true).into()
71+
})
72+
.collect::<Vec<_>>();
73+
let return_field_f64 = Field::new("f", DataType::Float64, true).into();
74+
75+
c.bench_function(&format!("atan2 f64 array: {size}"), |b| {
76+
b.iter(|| {
77+
black_box(
78+
atan2_fn
79+
.invoke_with_args(ScalarFunctionArgs {
80+
args: f64_args.clone(),
81+
arg_fields: f64_arg_fields.clone(),
82+
number_rows: size,
83+
return_field: Arc::clone(&return_field_f64),
84+
config_options: Arc::clone(&config_options),
85+
})
86+
.unwrap(),
87+
)
88+
})
89+
});
90+
}
91+
92+
let scalar_f32_args = vec![
93+
ColumnarValue::Scalar(ScalarValue::Float32(Some(1.0))),
94+
ColumnarValue::Scalar(ScalarValue::Float32(Some(2.0))),
95+
];
96+
let scalar_f32_arg_fields = vec![
97+
Field::new("a", DataType::Float32, false).into(),
98+
Field::new("b", DataType::Float32, false).into(),
99+
];
100+
let return_field_f32 = Field::new("f", DataType::Float32, false).into();
101+
102+
c.bench_function("atan2 f32 scalar", |b| {
103+
b.iter(|| {
104+
black_box(
105+
atan2_fn
106+
.invoke_with_args(ScalarFunctionArgs {
107+
args: scalar_f32_args.clone(),
108+
arg_fields: scalar_f32_arg_fields.clone(),
109+
number_rows: 1,
110+
return_field: Arc::clone(&return_field_f32),
111+
config_options: Arc::clone(&config_options),
112+
})
113+
.unwrap(),
114+
)
115+
})
116+
});
117+
118+
let scalar_f64_args = vec![
119+
ColumnarValue::Scalar(ScalarValue::Float64(Some(1.0))),
120+
ColumnarValue::Scalar(ScalarValue::Float64(Some(2.0))),
121+
];
122+
let scalar_f64_arg_fields = vec![
123+
Field::new("a", DataType::Float64, false).into(),
124+
Field::new("b", DataType::Float64, false).into(),
125+
];
126+
let return_field_f64 = Field::new("f", DataType::Float64, false).into();
127+
128+
c.bench_function("atan2 f64 scalar", |b| {
129+
b.iter(|| {
130+
black_box(
131+
atan2_fn
132+
.invoke_with_args(ScalarFunctionArgs {
133+
args: scalar_f64_args.clone(),
134+
arg_fields: scalar_f64_arg_fields.clone(),
135+
number_rows: 1,
136+
return_field: Arc::clone(&return_field_f64),
137+
config_options: Arc::clone(&config_options),
138+
})
139+
.unwrap(),
140+
)
141+
})
142+
});
143+
}
144+
145+
criterion_group!(benches, criterion_benchmark);
146+
criterion_main!(benches);

datafusion/functions/src/macros.rs

Lines changed: 71 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -332,7 +332,8 @@ macro_rules! make_math_binary_udf {
332332

333333
use arrow::array::{ArrayRef, AsArray};
334334
use arrow::datatypes::{DataType, Float32Type, Float64Type};
335-
use datafusion_common::{Result, exec_err};
335+
use datafusion_common::utils::take_function_args;
336+
use datafusion_common::{Result, ScalarValue, internal_err};
336337
use datafusion_expr::TypeSignature;
337338
use datafusion_expr::sort_properties::{ExprProperties, SortProperties};
338339
use datafusion_expr::{
@@ -393,37 +394,76 @@ macro_rules! make_math_binary_udf {
393394
&self,
394395
args: ScalarFunctionArgs,
395396
) -> Result<ColumnarValue> {
396-
let args = ColumnarValue::values_to_arrays(&args.args)?;
397-
let arr: ArrayRef = match args[0].data_type() {
398-
DataType::Float64 => {
399-
let y = args[0].as_primitive::<Float64Type>();
400-
let x = args[1].as_primitive::<Float64Type>();
401-
let result = arrow::compute::binary::<_, _, _, Float64Type>(
402-
y,
403-
x,
404-
|y, x| f64::$BINARY_FUNC(y, x),
405-
)?;
406-
Arc::new(result) as _
407-
}
408-
DataType::Float32 => {
409-
let y = args[0].as_primitive::<Float32Type>();
410-
let x = args[1].as_primitive::<Float32Type>();
411-
let result = arrow::compute::binary::<_, _, _, Float32Type>(
412-
y,
413-
x,
414-
|y, x| f32::$BINARY_FUNC(y, x),
415-
)?;
416-
Arc::new(result) as _
417-
}
418-
other => {
419-
return exec_err!(
420-
"Unsupported data type {other:?} for function {}",
421-
self.name()
422-
);
397+
let ScalarFunctionArgs {
398+
args, return_field, ..
399+
} = args;
400+
let return_type = return_field.data_type();
401+
let [y, x] = take_function_args(self.name(), args)?;
402+
403+
match (y, x) {
404+
(
405+
ColumnarValue::Scalar(y_scalar),
406+
ColumnarValue::Scalar(x_scalar),
407+
) => match (&y_scalar, &x_scalar) {
408+
(y, x) if y.is_null() || x.is_null() => {
409+
ColumnarValue::Scalar(ScalarValue::Null)
410+
.cast_to(return_type, None)
411+
}
412+
(
413+
ScalarValue::Float64(Some(yv)),
414+
ScalarValue::Float64(Some(xv)),
415+
) => Ok(ColumnarValue::Scalar(ScalarValue::Float64(Some(
416+
f64::$BINARY_FUNC(*yv, *xv),
417+
)))),
418+
(
419+
ScalarValue::Float32(Some(yv)),
420+
ScalarValue::Float32(Some(xv)),
421+
) => Ok(ColumnarValue::Scalar(ScalarValue::Float32(Some(
422+
f32::$BINARY_FUNC(*yv, *xv),
423+
)))),
424+
_ => internal_err!(
425+
"Unexpected scalar types for function {}: {:?}, {:?}",
426+
self.name(),
427+
y_scalar.data_type(),
428+
x_scalar.data_type()
429+
),
430+
},
431+
(y, x) => {
432+
let args = ColumnarValue::values_to_arrays(&[y, x])?;
433+
let arr: ArrayRef = match args[0].data_type() {
434+
DataType::Float64 => {
435+
let y = args[0].as_primitive::<Float64Type>();
436+
let x = args[1].as_primitive::<Float64Type>();
437+
let result =
438+
arrow::compute::binary::<_, _, _, Float64Type>(
439+
y,
440+
x,
441+
|y, x| f64::$BINARY_FUNC(y, x),
442+
)?;
443+
Arc::new(result) as _
444+
}
445+
DataType::Float32 => {
446+
let y = args[0].as_primitive::<Float32Type>();
447+
let x = args[1].as_primitive::<Float32Type>();
448+
let result =
449+
arrow::compute::binary::<_, _, _, Float32Type>(
450+
y,
451+
x,
452+
|y, x| f32::$BINARY_FUNC(y, x),
453+
)?;
454+
Arc::new(result) as _
455+
}
456+
other => {
457+
return internal_err!(
458+
"Unsupported data type {other:?} for function {}",
459+
self.name()
460+
);
461+
}
462+
};
463+
464+
Ok(ColumnarValue::Array(arr))
423465
}
424-
};
425-
426-
Ok(ColumnarValue::Array(arr))
466+
}
427467
}
428468

429469
fn documentation(&self) -> Option<&Documentation> {

0 commit comments

Comments
 (0)