Skip to content

Commit 9d1a049

Browse files
authored
Parquet dict string encoding bench (apache#11417)
# Which issue does this PR close? <!-- It is not necessary to raise an issue, but it is encouraged if it is a non-trivial enhancement/bug. If this PR relates to an existing issue, but does not fully resolve it, please change the wording below from "Closes #NNN" to "Relates to #NNN" or "Part of #NNN" to avoid false closing an issue. --> - related but does not complete apache#11414 - related apache/datafusion#24111 - related apache/datafusion#24117 (comment) # Rationale for this change see attached issue <!-- 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 try to explain the problem you are trying to solve in terms of the user-visible behavior, rather than the implementation. --> # What changes are included in this PR? adds new benchmarks for reading RLE_DICTIONARY into different arrow arrays. the focus being that reads should scale with cardinality <!-- 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. ran the benchmarks locally 😅 <!-- 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, if so identify these tests)? If this PR claims a performance improvement, please include evidence such as benchmark results. DO NOT simply paste a list of commands ran to verify the code; this is what our CI is for and it pollutes the PR. ONLY explain if testing was included with this PR, or why it wasn't. --> # Are there any significant user-facing changes? no <!-- Significant user-facing changes include: - Breaking public API change - Significant change to existing functionality (e.g. function returns something different) These need to be explicitly called out to ensure we have proper documentation if required and to ensure we follow proper semantic versioning. DO NOT restate the changes of this PR; if a bug was fixed and already explained above, we don't need this to be restated as a user-facing change. -->
1 parent 2d17a72 commit 9d1a049

2 files changed

Lines changed: 172 additions & 0 deletions

File tree

‎parquet/Cargo.toml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,11 @@ name = "arrow_reader_row_filter"
269269
required-features = ["arrow", "async"]
270270
harness = false
271271

272+
[[bench]]
273+
name = "arrow_reader_string_encoding"
274+
required-features = ["arrow"]
275+
harness = false
276+
272277
[[bench]]
273278
name = "arrow_reader_predicate_fusion"
274279
required-features = ["arrow", "async", "snap"]
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
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+
//! Benchmark comparing reading the SAME dictionary-encoded parquet string column
19+
//! back as two different Arrow logical types:
20+
//! 1. `Dictionary(Int32, Utf8)`
21+
//! 2. `Utf8View`
22+
//!
23+
//! Sweeps cardinality in {10, 100, 1000, 20_000} and row count
24+
//! in {1M, 5M}, writing a dictionary-encoded parquet file in-memory
25+
//! and measuring only the read time via `ArrowReaderOptions::with_schema`.
26+
27+
use std::sync::Arc;
28+
29+
use arrow_array::{ArrayRef, RecordBatch, StringArray};
30+
use arrow_schema::{DataType, Field, Schema, SchemaRef};
31+
use bytes::Bytes;
32+
use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
33+
use parquet::arrow::ArrowWriter;
34+
use parquet::arrow::arrow_reader::{ArrowReaderOptions, ParquetRecordBatchReaderBuilder};
35+
use parquet::basic::Compression;
36+
use parquet::file::properties::WriterProperties;
37+
use rand::{RngExt, SeedableRng, rngs::StdRng};
38+
39+
/// Lengths chosen to exercise both the inlined Utf8View path (<= 12 bytes) and
40+
/// the out-of-line buffer path (> 12 bytes).
41+
const STRING_LENS: &[usize] = &[8, 24];
42+
const SEED: u64 = 0xC0FFEE_u64;
43+
const CARDINALITIES: &[usize] = &[10, 100, 1000, 20_000];
44+
const ROW_COUNTS: &[usize] = &[1_000_000, 5_000_000];
45+
const NULL_FRACTIONS: &[f64] = &[0.0, 0.5];
46+
const NULL_PROB_DENOM: u32 = 1_000_000;
47+
const BATCH_SIZE: usize = 8192;
48+
49+
fn build_value_pool(cardinality: usize, string_len: usize) -> Vec<String> {
50+
(0..cardinality)
51+
.map(|idx| format!("{idx:0string_len$}"))
52+
.collect()
53+
}
54+
55+
fn make_string_array(
56+
cardinality: usize,
57+
num_rows: usize,
58+
null_fraction: f64,
59+
string_len: usize,
60+
) -> StringArray {
61+
let dictionary = build_value_pool(cardinality, string_len);
62+
debug_assert_eq!(dictionary[0].len(), string_len);
63+
let mut rng = StdRng::seed_from_u64(
64+
SEED ^ cardinality as u64 ^ num_rows as u64 ^ null_fraction.to_bits() ^ string_len as u64,
65+
);
66+
let null_threshold = (null_fraction * NULL_PROB_DENOM as f64) as u32;
67+
let values: Vec<Option<&str>> = (0..num_rows)
68+
.map(|_| {
69+
if null_fraction > 0.0 && rng.random_range(0..NULL_PROB_DENOM) < null_threshold {
70+
None
71+
} else {
72+
let pick = rng.random_range(0..cardinality);
73+
Some(dictionary[pick].as_str())
74+
}
75+
})
76+
.collect();
77+
StringArray::from(values)
78+
}
79+
80+
fn write_parquet(column: StringArray) -> Bytes {
81+
let schema: SchemaRef = Arc::new(Schema::new(vec![Field::new("value", DataType::Utf8, true)]));
82+
let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(column) as ArrayRef]).unwrap();
83+
84+
let props = WriterProperties::builder()
85+
.set_dictionary_enabled(true)
86+
.set_compression(Compression::UNCOMPRESSED)
87+
.build();
88+
89+
let mut buffer: Vec<u8> = Vec::with_capacity(64 * 1024 * 1024);
90+
let mut writer = ArrowWriter::try_new(&mut buffer, schema, Some(props)).unwrap();
91+
writer.write(&batch).unwrap();
92+
writer.close().unwrap();
93+
Bytes::from(buffer)
94+
}
95+
96+
fn override_schema(data_type: DataType) -> SchemaRef {
97+
Arc::new(Schema::new(vec![Field::new("value", data_type, true)]))
98+
}
99+
100+
fn read_as(file_bytes: &Bytes, schema: SchemaRef) -> usize {
101+
let options = ArrowReaderOptions::new().with_schema(schema);
102+
let reader = ParquetRecordBatchReaderBuilder::try_new_with_options(file_bytes.clone(), options)
103+
.unwrap()
104+
.with_batch_size(BATCH_SIZE)
105+
.build()
106+
.unwrap();
107+
let mut total_rows = 0;
108+
for maybe_batch in reader {
109+
let batch = maybe_batch.unwrap();
110+
total_rows += batch.num_rows();
111+
}
112+
total_rows
113+
}
114+
115+
fn criterion_benchmark(criterion: &mut Criterion) {
116+
let dict_schema = override_schema(DataType::Dictionary(
117+
Box::new(DataType::Int32),
118+
Box::new(DataType::Utf8),
119+
));
120+
let utf8_view_schema = override_schema(DataType::Utf8View);
121+
122+
for &num_rows in ROW_COUNTS {
123+
for &cardinality in CARDINALITIES {
124+
for &null_fraction in NULL_FRACTIONS {
125+
for &string_len in STRING_LENS {
126+
let column =
127+
make_string_array(cardinality, num_rows, null_fraction, string_len);
128+
let file_bytes = write_parquet(column);
129+
130+
let mut group = criterion.benchmark_group("RLE_DICTIONARY_read");
131+
group.sample_size(10);
132+
group.throughput(criterion::Throughput::Elements(num_rows as u64));
133+
134+
let param = format!(
135+
"rows={num_rows}/card={cardinality}/nulls={null_fraction:.2}/len={string_len}"
136+
);
137+
138+
group.bench_with_input(
139+
BenchmarkId::new("Dictionary(Int32,Utf8)", &param),
140+
&param,
141+
|bencher, _| {
142+
bencher.iter(|| {
143+
let rows = read_as(&file_bytes, dict_schema.clone());
144+
assert_eq!(rows, num_rows);
145+
});
146+
},
147+
);
148+
group.bench_with_input(
149+
BenchmarkId::new("Utf8View", &param),
150+
&param,
151+
|bencher, _| {
152+
bencher.iter(|| {
153+
let rows = read_as(&file_bytes, utf8_view_schema.clone());
154+
assert_eq!(rows, num_rows);
155+
});
156+
},
157+
);
158+
159+
group.finish();
160+
}
161+
}
162+
}
163+
}
164+
}
165+
166+
criterion_group!(benches, criterion_benchmark);
167+
criterion_main!(benches);

0 commit comments

Comments
 (0)