Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Faster timestamp parsing (~70-90% faster) #3801

Merged
merged 7 commits into from
Mar 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 31 additions & 28 deletions arrow-array/src/timezone.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,29 +18,34 @@
//! Timezone for timestamp arrays

use arrow_schema::ArrowError;
use chrono::format::{parse, Parsed, StrftimeItems};
use chrono::FixedOffset;
pub use private::{Tz, TzOffset};

/// Parses a fixed offset of the form "+09:00"
fn parse_fixed_offset(tz: &str) -> Result<FixedOffset, ArrowError> {
let mut parsed = Parsed::new();

if let Ok(fixed_offset) = parse(&mut parsed, tz, StrftimeItems::new("%:z"))
.and_then(|_| parsed.to_fixed_offset())
{
return Ok(fixed_offset);
/// Parses a fixed offset of the form "+09:00", "-09" or "+0930"
fn parse_fixed_offset(tz: &str) -> Option<FixedOffset> {
let bytes = tz.as_bytes();

let mut values = match bytes.len() {
// [+-]XX:XX
6 if bytes[3] == b':' => [bytes[1], bytes[2], bytes[4], bytes[5]],
// [+-]XXXX
5 => [bytes[1], bytes[2], bytes[3], bytes[4]],
// [+-]XX
3 => [bytes[1], bytes[2], b'0', b'0'],
_ => return None,
};
values.iter_mut().for_each(|x| *x = x.wrapping_sub(b'0'));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this converts the ascii to the numeric representation, right? I am thinking that the use of wrapping sub ensures that any values like (20) that is lower than '0' will not pass this check, is that correct?

Copy link
Contributor Author

@tustvold tustvold Mar 8, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wrapping sub will just underflow harmlessly for such values, which will then fail on the check for < 9

if values.iter().any(|x| *x > 9) {
return None;
}
let secs = (values[0] * 10 + values[1]) as i32 * 60 * 60
+ (values[2] * 10 + values[3]) as i32 * 60;

if let Ok(fixed_offset) = parse(&mut parsed, tz, StrftimeItems::new("%#z"))
.and_then(|_| parsed.to_fixed_offset())
{
return Ok(fixed_offset);
match bytes[0] {
b'+' => FixedOffset::east_opt(secs),
b'-' => FixedOffset::west_opt(secs),
_ => None,
}

Err(ArrowError::ParseError(format!(
"Invalid timezone \"{tz}\": Expected format [+-]XX:XX, [+-]XX, or [+-]XXXX"
)))
}

#[cfg(feature = "chrono-tz")]
Expand Down Expand Up @@ -83,12 +88,11 @@ mod private {
type Err = ArrowError;

fn from_str(tz: &str) -> Result<Self, Self::Err> {
if tz.starts_with('+') || tz.starts_with('-') {
Ok(Self(TzInner::Offset(parse_fixed_offset(tz)?)))
} else {
Ok(Self(TzInner::Timezone(tz.parse().map_err(|e| {
match parse_fixed_offset(tz) {
Some(offset) => Ok(Self(TzInner::Offset(offset))),
None => Ok(Self(TzInner::Timezone(tz.parse().map_err(|e| {
ArrowError::ParseError(format!("Invalid timezone \"{tz}\": {e}"))
})?)))
})?))),
}
}
}
Expand Down Expand Up @@ -261,13 +265,12 @@ mod private {
type Err = ArrowError;

fn from_str(tz: &str) -> Result<Self, Self::Err> {
if tz.starts_with('+') || tz.starts_with('-') {
Ok(Self(parse_fixed_offset(tz)?))
} else {
Err(ArrowError::ParseError(format!(
let offset = parse_fixed_offset(tz).ok_or_else(|| {
ArrowError::ParseError(format!(
"Invalid timezone \"{tz}\": only offset based timezones supported without chrono-tz feature"
)))
}
))
})?;
Ok(Self(offset))
}
}

Expand Down
5 changes: 5 additions & 0 deletions arrow-cast/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,10 @@ num = { version = "0.4", default-features = false, features = ["std"] }
lexical-core = { version = "^0.8", default-features = false, features = ["write-integers", "write-floats", "parse-integers", "parse-floats"] }

[dev-dependencies]
criterion = { version = "0.4", default-features = false }

[build-dependencies]

[[bench]]
name = "parse_timestamp"
harness = false
44 changes: 44 additions & 0 deletions arrow-cast/benches/parse_timestamp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

use arrow_cast::parse::string_to_timestamp_nanos;
use criterion::*;

fn criterion_benchmark(c: &mut Criterion) {
let timestamps = [
"2020-09-08",
"2020-09-08T13:42:29",
"2020-09-08T13:42:29.190",
"2020-09-08T13:42:29.190855",
"2020-09-08T13:42:29.190855999",
"2020-09-08T13:42:29+00:00",
"2020-09-08T13:42:29.190+00:00",
"2020-09-08T13:42:29.190855+00:00",
"2020-09-08T13:42:29.190855999-05:00",
"2020-09-08T13:42:29.190855Z",
];

for timestamp in timestamps {
let t = black_box(timestamp);
c.bench_function(t, |b| {
b.iter(|| string_to_timestamp_nanos(t).unwrap());
});
}
}

criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
10 changes: 7 additions & 3 deletions arrow-cast/src/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4785,7 +4785,7 @@ mod tests {
let err = cast_with_options(array, &to_type, &options).unwrap_err();
assert_eq!(
err.to_string(),
"Cast error: Error parsing 'Not a valid date' as timestamp"
"Parser error: Error parsing timestamp from 'Not a valid date': error parsing date"
);
}
}
Expand Down Expand Up @@ -7601,8 +7601,12 @@ mod tests {
]);

let array = Arc::new(valid) as ArrayRef;
let b = cast(&array, &DataType::Timestamp(TimeUnit::Nanosecond, Some(tz)))
.unwrap();
let b = cast_with_options(
&array,
&DataType::Timestamp(TimeUnit::Nanosecond, Some(tz)),
&CastOptions { safe: false },
)
.unwrap();

let c = b
.as_any()
Expand Down
Loading