Skip to content

Commit ea0da8b

Browse files
Add benchmarks for dictionary path of new_group_values (#22004)
## Which issue does this PR close? benchmarks for #21765. Also related to #21860 The goal is to merge this PR and then rebase the branch on #21765 to contain these benchmarks, so that they can be run and compared to the original. <!-- 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. --> ## Rationale for this change Originally this was included in #21765 but that PR is already very large. I decided to move it to its own separate PR <!-- 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? Adds benchmarks for the dictionary encoding array path of **new_group_values()**. <!-- 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? n/a <!-- 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: Kumar Ujjawal <ujjawalpathak6@gmail.com>
1 parent 2bf1db5 commit ea0da8b

2 files changed

Lines changed: 180 additions & 0 deletions

File tree

datafusion/physical-plan/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,3 +112,7 @@ required-features = ["test_utils"]
112112
harness = false
113113
name = "aggregate_vectorized"
114114
required-features = ["test_utils"]
115+
116+
[[bench]]
117+
harness = false
118+
name = "dictionary_group_values"
Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
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+
//! Benchmarks for `GroupValues` over a single `Dictionary<Int32, Utf8>`
19+
//! column. Each iteration measures `intern` (once or N times) followed by
20+
//! `emit(EmitTo::All)`. The `Box<dyn GroupValues>` returned by
21+
//! `new_group_values` is constructed in the setup closure of
22+
//! `iter_batched_ref` and is not included in the timing.
23+
24+
use arrow::array::{ArrayRef, DictionaryArray, PrimitiveArray, StringArray};
25+
use arrow::buffer::{Buffer, NullBuffer};
26+
use arrow::datatypes::{DataType, Field, Int32Type, Schema, SchemaRef};
27+
use criterion::{
28+
BatchSize, BenchmarkId, Criterion, Throughput, criterion_group, criterion_main,
29+
};
30+
use datafusion_expr::EmitTo;
31+
use datafusion_physical_plan::aggregates::group_values::new_group_values;
32+
use datafusion_physical_plan::aggregates::order::GroupOrdering;
33+
use rand::rngs::StdRng;
34+
use rand::seq::SliceRandom;
35+
use rand::{Rng, SeedableRng};
36+
use std::hint::black_box;
37+
use std::sync::Arc;
38+
39+
const SIZES: [usize; 2] = [8 * 1024, 64 * 1024];
40+
const CARDS_RELATIVE: [usize; 4] = [20, 75, 300, 1000];
41+
const N_BATCHES: usize = 4;
42+
// Fixed for reproducibility.
43+
const SEED: u64 = 0xD1C7;
44+
45+
fn dict_schema() -> SchemaRef {
46+
let dict_ty =
47+
DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8));
48+
Arc::new(Schema::new(vec![Field::new("g", dict_ty, true)]))
49+
}
50+
51+
/// Build a `Dictionary<Int32, Utf8>` column.
52+
fn make_dict(size: usize, cardinality: usize, null_density: f32, seed: u64) -> ArrayRef {
53+
let strings: Vec<String> = (0..cardinality).map(|i| format!("v_{i:08}")).collect();
54+
let values = Arc::new(StringArray::from(
55+
strings.iter().map(String::as_str).collect::<Vec<_>>(),
56+
));
57+
58+
let mut rng = StdRng::seed_from_u64(seed);
59+
let keys: Vec<i32> = if cardinality == size {
60+
let mut perm: Vec<i32> = (0..size as i32).collect();
61+
perm.shuffle(&mut rng);
62+
perm
63+
} else {
64+
(0..size)
65+
.map(|_| rng.random_range(0..cardinality) as i32)
66+
.collect()
67+
};
68+
let keys_buf = Buffer::from_slice_ref(&keys);
69+
70+
let nulls: Option<NullBuffer> = (null_density > 0.0).then(|| {
71+
(0..size)
72+
.map(|_| !rng.random_bool(null_density as f64))
73+
.collect()
74+
});
75+
76+
let key_array = PrimitiveArray::<Int32Type>::new(keys_buf.into(), nulls);
77+
Arc::new(DictionaryArray::<Int32Type>::try_new(key_array, values).unwrap())
78+
}
79+
80+
fn bench_id(
81+
label: &str,
82+
size: usize,
83+
cardinality: usize,
84+
null_density: f32,
85+
) -> BenchmarkId {
86+
BenchmarkId::new(
87+
label,
88+
format!("size_{size}_card_{cardinality}_null_{null_density:.2}"),
89+
)
90+
}
91+
92+
fn bench_intern_emit(c: &mut Criterion) {
93+
let mut group = c.benchmark_group("dict_intern_emit");
94+
let schema = dict_schema();
95+
let null_density = 0.0;
96+
97+
for &size in &SIZES {
98+
let mut cards = CARDS_RELATIVE.to_vec();
99+
cards.push(size); // all-unique stress case
100+
for cardinality in cards {
101+
let array = make_dict(size, cardinality, null_density, SEED);
102+
group.throughput(Throughput::Elements(size as u64));
103+
group.bench_function(
104+
bench_id("intern_emit", size, cardinality, null_density),
105+
|b| {
106+
b.iter_batched_ref(
107+
|| {
108+
(
109+
new_group_values(schema.clone(), &GroupOrdering::None)
110+
.unwrap(),
111+
Vec::<usize>::with_capacity(size),
112+
)
113+
},
114+
|(gv, groups)| {
115+
gv.intern(std::slice::from_ref(&array), groups).unwrap();
116+
black_box(&*groups);
117+
black_box(gv.emit(EmitTo::All).unwrap());
118+
},
119+
BatchSize::SmallInput,
120+
);
121+
},
122+
);
123+
}
124+
}
125+
group.finish();
126+
}
127+
128+
fn bench_repeated_intern_emit(c: &mut Criterion) {
129+
let mut group = c.benchmark_group("dict_repeated_intern_emit");
130+
let schema = dict_schema();
131+
let null_density = 0.10;
132+
133+
for &size in &SIZES {
134+
let mut cards = CARDS_RELATIVE.to_vec();
135+
cards.push(size);
136+
for cardinality in cards {
137+
let batches: Vec<ArrayRef> = (0..N_BATCHES)
138+
.map(|i| {
139+
make_dict(
140+
size,
141+
cardinality,
142+
null_density,
143+
SEED.wrapping_add(i as u64),
144+
)
145+
})
146+
.collect();
147+
group.throughput(Throughput::Elements((size * N_BATCHES) as u64));
148+
group.bench_function(
149+
bench_id("repeated_intern_emit", size, cardinality, null_density),
150+
|b| {
151+
b.iter_batched_ref(
152+
|| {
153+
(
154+
new_group_values(schema.clone(), &GroupOrdering::None)
155+
.unwrap(),
156+
Vec::<usize>::with_capacity(size),
157+
)
158+
},
159+
|(gv, groups)| {
160+
for arr in &batches {
161+
gv.intern(std::slice::from_ref(arr), groups).unwrap();
162+
black_box(&*groups);
163+
}
164+
black_box(gv.emit(EmitTo::All).unwrap());
165+
},
166+
BatchSize::SmallInput,
167+
);
168+
},
169+
);
170+
}
171+
}
172+
group.finish();
173+
}
174+
175+
criterion_group!(benches, bench_intern_emit, bench_repeated_intern_emit);
176+
criterion_main!(benches);

0 commit comments

Comments
 (0)