Skip to content

Commit 22f9a92

Browse files
niebayesAdamGS
andauthored
perf(range): avoid eager ok_or in gen_range_timestamp (#25308)
## What I did Replace per-row `ok_or(exec_datafusion_err!(...))` with `ok_or_else` in `gen_range_timestamp` so the success path no longer allocates a DataFusionError for every generated row (speed up ~5x on 100k rows). Add a criterion bench for the timestamp range path. ``` shell # Before, with eager ok_or range_timestamp_100000 time: [60.762 ms 60.815 ms 60.868 ms] # After, with lazy ok_or_else range_timestamp_100000 time: [12.390 ms 12.401 ms 12.413 ms] change: [−79.634% −79.608% −79.582%] (p = 0.00 < 0.05) Performance has improved. ``` ## 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 #25307 . ## Rationale for this change <!-- 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. Please explain the problem you are trying to solve in terms of the user-visible behavior, rather than the implementation. For example, "The code in `foo.rs` doesn't handle nulls" is a symptom of the implementation. "COUNT(DISTINCT) returns wrong results when the column contains nulls" is the user-visible problem. --> Avoid eager ok_or on the hot path. ## What changes are included in this PR? <!-- 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. --> Replaces eager ok_or with lazy ok_or_else. ## What is the testing strategy for this PR? <!-- 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 Briefly describe how this PR is tested, and point to the specific tests you added. For example: 'This new feature is covered by the `sqllogictest` cases added in `foo.slt`'. If this PR does not add tests, explain why. For example, if the change is already covered by existing tests, please mention it. You should also check the `codecov` bot reply on this PR to confirm the changed code is exercised. --> Added a criterion bench. ## Are there any user-facing changes? <!-- 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. --> No --------- Co-authored-by: Adam Gutglick <[email protected]>
1 parent c4f72ba commit 22f9a92

3 files changed

Lines changed: 121 additions & 13 deletions

File tree

‎datafusion/functions-nested/Cargo.toml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,3 +145,7 @@ name = "array_range"
145145
[[bench]]
146146
harness = false
147147
name = "cardinality"
148+
149+
[[bench]]
150+
harness = false
151+
name = "range"
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
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+
use std::hint::black_box;
19+
use std::sync::Arc;
20+
21+
use arrow::array::IntervalMonthDayNanoArray;
22+
use arrow::array::TimestampNanosecondArray;
23+
use arrow::datatypes::{
24+
DataType, Field, IntervalMonthDayNanoType, IntervalUnit, TimeUnit,
25+
};
26+
use criterion::{Criterion, criterion_group, criterion_main};
27+
use datafusion_common::config::ConfigOptions;
28+
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl};
29+
use datafusion_functions_nested::range::Range;
30+
use rand::rngs::StdRng;
31+
use rand::{Rng, SeedableRng};
32+
33+
const NUM_ROWS: usize = 100_000;
34+
const NANOS_PER_SECOND: i64 = 1_000_000_000;
35+
36+
fn range_timestamp(c: &mut Criterion) {
37+
let mut rng = StdRng::seed_from_u64(42);
38+
// ~2016-era timestamps; each row generates a 1-second range (1 element),
39+
// so the per-row timestamp-range setup dominates the measurement.
40+
let start: TimestampNanosecondArray = (0..NUM_ROWS)
41+
.map(|_| {
42+
Some(1_452_499_200_000_000_000i64 + rng.random_range(0..NANOS_PER_SECOND))
43+
})
44+
.collect();
45+
let stop: TimestampNanosecondArray = start
46+
.iter()
47+
.map(|v| v.map(|v| v + NANOS_PER_SECOND))
48+
.collect();
49+
let step = IntervalMonthDayNanoArray::from(vec![
50+
IntervalMonthDayNanoType::make_value(
51+
0,
52+
0,
53+
NANOS_PER_SECOND
54+
);
55+
NUM_ROWS
56+
]);
57+
58+
let udf = Range::new();
59+
let ts_type = DataType::Timestamp(TimeUnit::Nanosecond, None);
60+
let return_type = udf
61+
.return_type(&[
62+
ts_type.clone(),
63+
ts_type.clone(),
64+
DataType::Interval(IntervalUnit::MonthDayNano),
65+
])
66+
.unwrap();
67+
let return_field = Arc::new(Field::new("f", return_type, true));
68+
69+
let arg_fields = vec![
70+
Field::new("a", ts_type.clone(), true).into(),
71+
Field::new("b", ts_type, true).into(),
72+
Field::new("c", DataType::Interval(IntervalUnit::MonthDayNano), true).into(),
73+
];
74+
let config_options = Arc::new(ConfigOptions::default());
75+
let args = vec![
76+
ColumnarValue::Array(Arc::new(start)),
77+
ColumnarValue::Array(Arc::new(stop)),
78+
ColumnarValue::Array(Arc::new(step)),
79+
];
80+
81+
c.bench_function(&format!("range_timestamp_{NUM_ROWS}"), |b| {
82+
b.iter(|| {
83+
black_box(
84+
udf.invoke_with_args(ScalarFunctionArgs {
85+
args: args.clone(),
86+
arg_fields: arg_fields.clone(),
87+
number_rows: NUM_ROWS,
88+
return_field: Arc::clone(&return_field),
89+
config_options: Arc::clone(&config_options),
90+
})
91+
.expect("range should work on valid values"),
92+
)
93+
})
94+
});
95+
}
96+
97+
criterion_group!(benches, range_timestamp);
98+
criterion_main!(benches);

‎datafusion/functions-nested/src/range.rs‎

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -461,28 +461,34 @@ impl Range {
461461
}
462462

463463
let neg = TimestampNanosecondType::add_month_day_nano(start, step, start_tz)
464-
.ok_or(exec_datafusion_err!(
465-
"Cannot generate timestamp range where start + step overflows"
466-
))?
464+
.ok_or_else(|| {
465+
exec_datafusion_err!(
466+
"Cannot generate timestamp range where start + step overflows"
467+
)
468+
})?
467469
.cmp(&start)
468470
== Ordering::Less;
469471

470472
let stop_dt =
471473
as_datetime_with_timezone::<TimestampNanosecondType>(stop, stop_tz)
472-
.ok_or(exec_datafusion_err!(
473-
"Cannot generate timestamp for stop: {}: {:?}",
474-
stop,
475-
stop_tz
476-
))?;
474+
.ok_or_else(|| {
475+
exec_datafusion_err!(
476+
"Cannot generate timestamp for stop: {}: {:?}",
477+
stop,
478+
stop_tz
479+
)
480+
})?;
477481

478482
let mut current = start;
479483
let mut current_dt =
480484
as_datetime_with_timezone::<TimestampNanosecondType>(current, start_tz)
481-
.ok_or(exec_datafusion_err!(
482-
"Cannot generate timestamp for start: {}: {:?}",
483-
current,
484-
start_tz
485-
))?;
485+
.ok_or_else(|| {
486+
exec_datafusion_err!(
487+
"Cannot generate timestamp for start: {}: {:?}",
488+
current,
489+
start_tz
490+
)
491+
})?;
486492

487493
let values = from_fn(|| {
488494
let generate_series_should_end = self.include_upper_bound

0 commit comments

Comments
 (0)