Skip to content

Commit 9c0edcc

Browse files
authored
chore: add count distinct group benchmarks (#21575)
## Which issue does this PR close? Add benchmarks for group accumulators to test : #21561 The implementation forks out based on `is_groups_accumulator_supported` function call. Once this is merged , we should be able to evaluate group accumulators on count distinct expr <!-- 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 #. ## 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. --> ## 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. --> ## Are these changes tested? <!-- 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? <!-- 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 7e1a710 commit 9c0edcc

File tree

1 file changed

+308
-3
lines changed

1 file changed

+308
-3
lines changed

datafusion/functions-aggregate/benches/count_distinct.rs

Lines changed: 308 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,13 @@
1818
use std::sync::Arc;
1919

2020
use arrow::array::{
21-
ArrayRef, Int8Array, Int16Array, Int64Array, UInt8Array, UInt16Array,
21+
Array, ArrayRef, Int8Array, Int16Array, Int32Array, Int64Array, UInt8Array,
22+
UInt16Array, UInt32Array,
2223
};
2324
use arrow::datatypes::{DataType, Field, Schema};
2425
use criterion::{Criterion, criterion_group, criterion_main};
2526
use datafusion_expr::function::AccumulatorArgs;
26-
use datafusion_expr::{Accumulator, AggregateUDFImpl};
27+
use datafusion_expr::{Accumulator, AggregateUDFImpl, EmitTo};
2728
use datafusion_functions_aggregate::count::Count;
2829
use datafusion_physical_expr::expressions::col;
2930
use rand::rngs::StdRng;
@@ -87,6 +88,44 @@ fn create_i16_array(n_distinct: usize) -> Int16Array {
8788
.collect()
8889
}
8990

91+
fn create_u32_array(n_distinct: usize) -> UInt32Array {
92+
let mut rng = StdRng::seed_from_u64(42);
93+
(0..BATCH_SIZE)
94+
.map(|_| Some(rng.random_range(0..n_distinct as u32)))
95+
.collect()
96+
}
97+
98+
fn create_i32_array(n_distinct: usize) -> Int32Array {
99+
let mut rng = StdRng::seed_from_u64(42);
100+
(0..BATCH_SIZE)
101+
.map(|_| Some(rng.random_range(0..n_distinct as i32)))
102+
.collect()
103+
}
104+
105+
fn prepare_args(data_type: DataType) -> (Arc<Schema>, AccumulatorArgs<'static>) {
106+
let schema = Arc::new(Schema::new(vec![Field::new("f", data_type, true)]));
107+
let schema_leaked: &'static Schema = Box::leak(Box::new((*schema).clone()));
108+
let expr = col("f", schema_leaked).unwrap();
109+
let expr_leaked: &'static _ = Box::leak(Box::new(expr));
110+
let return_field: Arc<Field> = Field::new("f", DataType::Int64, true).into();
111+
let return_field_leaked: &'static _ = Box::leak(Box::new(return_field.clone()));
112+
let expr_field = expr_leaked.return_field(schema_leaked).unwrap();
113+
let expr_field_leaked: &'static _ = Box::leak(Box::new(expr_field));
114+
115+
let accumulator_args = AccumulatorArgs {
116+
return_field: return_field_leaked.clone(),
117+
schema: schema_leaked,
118+
expr_fields: std::slice::from_ref(expr_field_leaked),
119+
ignore_nulls: false,
120+
order_bys: &[],
121+
is_reversed: false,
122+
name: "count(distinct f)",
123+
is_distinct: true,
124+
exprs: std::slice::from_ref(expr_leaked),
125+
};
126+
(schema, accumulator_args)
127+
}
128+
90129
fn count_distinct_benchmark(c: &mut Criterion) {
91130
for pct in [80, 99] {
92131
let n_distinct = BATCH_SIZE * pct / 100;
@@ -148,7 +187,273 @@ fn count_distinct_benchmark(c: &mut Criterion) {
148187
.unwrap()
149188
})
150189
});
190+
191+
// 32-bit integer types
192+
for pct in [80, 99] {
193+
let n_distinct = BATCH_SIZE * pct / 100;
194+
195+
// UInt32
196+
let values = Arc::new(create_u32_array(n_distinct)) as ArrayRef;
197+
c.bench_function(&format!("count_distinct u32 {pct}% distinct"), |b| {
198+
b.iter(|| {
199+
let mut accumulator = prepare_accumulator(DataType::UInt32);
200+
accumulator
201+
.update_batch(std::slice::from_ref(&values))
202+
.unwrap()
203+
})
204+
});
205+
206+
// Int32
207+
let values = Arc::new(create_i32_array(n_distinct)) as ArrayRef;
208+
c.bench_function(&format!("count_distinct i32 {pct}% distinct"), |b| {
209+
b.iter(|| {
210+
let mut accumulator = prepare_accumulator(DataType::Int32);
211+
accumulator
212+
.update_batch(std::slice::from_ref(&values))
213+
.unwrap()
214+
})
215+
});
216+
}
217+
}
218+
219+
/// Create group indices with uniform distribution
220+
fn create_uniform_groups(num_groups: usize) -> Vec<usize> {
221+
let mut rng = StdRng::seed_from_u64(42);
222+
(0..BATCH_SIZE)
223+
.map(|_| rng.random_range(0..num_groups))
224+
.collect()
225+
}
226+
227+
/// Create group indices with skewed distribution (80% in 20% of groups)
228+
fn create_skewed_groups(num_groups: usize) -> Vec<usize> {
229+
let mut rng = StdRng::seed_from_u64(42);
230+
let hot_groups = (num_groups / 5).max(1);
231+
(0..BATCH_SIZE)
232+
.map(|_| {
233+
if rng.random_range(0..100) < 80 {
234+
rng.random_range(0..hot_groups)
235+
} else {
236+
rng.random_range(0..num_groups)
237+
}
238+
})
239+
.collect()
240+
}
241+
242+
fn count_distinct_groups_benchmark(c: &mut Criterion) {
243+
let count_fn = Count::new();
244+
245+
let group_counts = [100, 1000, 10000];
246+
let cardinalities = [("low", 20), ("mid", 80), ("high", 99)];
247+
let distributions = ["uniform", "skewed"];
248+
249+
// i64 benchmarks
250+
for num_groups in group_counts {
251+
for (card_name, distinct_pct) in cardinalities {
252+
for dist in distributions {
253+
let name = format!("i64_g{num_groups}_{card_name}_{dist}");
254+
let n_distinct = BATCH_SIZE * distinct_pct / 100;
255+
let values = Arc::new(create_i64_array(n_distinct)) as ArrayRef;
256+
let group_indices = if dist == "uniform" {
257+
create_uniform_groups(num_groups)
258+
} else {
259+
create_skewed_groups(num_groups)
260+
};
261+
262+
let (_schema, args) = prepare_args(DataType::Int64);
263+
264+
if count_fn.groups_accumulator_supported(args.clone()) {
265+
c.bench_function(&format!("count_distinct_groups {name}"), |b| {
266+
b.iter(|| {
267+
let mut acc =
268+
count_fn.create_groups_accumulator(args.clone()).unwrap();
269+
acc.update_batch(
270+
std::slice::from_ref(&values),
271+
&group_indices,
272+
None,
273+
num_groups,
274+
)
275+
.unwrap();
276+
acc.evaluate(EmitTo::All).unwrap()
277+
})
278+
});
279+
} else {
280+
let arr = values.as_any().downcast_ref::<Int64Array>().unwrap();
281+
let mut group_rows: Vec<Vec<i64>> = vec![Vec::new(); num_groups];
282+
for (idx, &group_idx) in group_indices.iter().enumerate() {
283+
if arr.is_valid(idx) {
284+
group_rows[group_idx].push(arr.value(idx));
285+
}
286+
}
287+
let group_arrays: Vec<ArrayRef> = group_rows
288+
.iter()
289+
.map(|rows| Arc::new(Int64Array::from(rows.clone())) as ArrayRef)
290+
.collect();
291+
292+
c.bench_function(&format!("count_distinct_groups {name}"), |b| {
293+
b.iter(|| {
294+
let mut accumulators: Vec<_> = (0..num_groups)
295+
.map(|_| prepare_accumulator(DataType::Int64))
296+
.collect();
297+
298+
for (group_idx, batch) in group_arrays.iter().enumerate() {
299+
if !batch.is_empty() {
300+
accumulators[group_idx]
301+
.update_batch(std::slice::from_ref(batch))
302+
.unwrap();
303+
}
304+
}
305+
306+
let _results: Vec<_> = accumulators
307+
.iter_mut()
308+
.map(|acc| acc.evaluate().unwrap())
309+
.collect();
310+
})
311+
});
312+
}
313+
}
314+
}
315+
}
316+
317+
// i32 benchmarks
318+
for num_groups in group_counts {
319+
for (card_name, distinct_pct) in cardinalities {
320+
for dist in distributions {
321+
let name = format!("i32_g{num_groups}_{card_name}_{dist}");
322+
let n_distinct = BATCH_SIZE * distinct_pct / 100;
323+
let values = Arc::new(create_i32_array(n_distinct)) as ArrayRef;
324+
let group_indices = if dist == "uniform" {
325+
create_uniform_groups(num_groups)
326+
} else {
327+
create_skewed_groups(num_groups)
328+
};
329+
330+
let (_schema, args) = prepare_args(DataType::Int32);
331+
332+
if count_fn.groups_accumulator_supported(args.clone()) {
333+
c.bench_function(&format!("count_distinct_groups {name}"), |b| {
334+
b.iter(|| {
335+
let mut acc =
336+
count_fn.create_groups_accumulator(args.clone()).unwrap();
337+
acc.update_batch(
338+
std::slice::from_ref(&values),
339+
&group_indices,
340+
None,
341+
num_groups,
342+
)
343+
.unwrap();
344+
acc.evaluate(EmitTo::All).unwrap()
345+
})
346+
});
347+
} else {
348+
let arr = values.as_any().downcast_ref::<Int32Array>().unwrap();
349+
let mut group_rows: Vec<Vec<i32>> = vec![Vec::new(); num_groups];
350+
for (idx, &group_idx) in group_indices.iter().enumerate() {
351+
if arr.is_valid(idx) {
352+
group_rows[group_idx].push(arr.value(idx));
353+
}
354+
}
355+
let group_arrays: Vec<ArrayRef> = group_rows
356+
.iter()
357+
.map(|rows| Arc::new(Int32Array::from(rows.clone())) as ArrayRef)
358+
.collect();
359+
360+
c.bench_function(&format!("count_distinct_groups {name}"), |b| {
361+
b.iter(|| {
362+
let mut accumulators: Vec<_> = (0..num_groups)
363+
.map(|_| prepare_accumulator(DataType::Int32))
364+
.collect();
365+
366+
for (group_idx, batch) in group_arrays.iter().enumerate() {
367+
if !batch.is_empty() {
368+
accumulators[group_idx]
369+
.update_batch(std::slice::from_ref(batch))
370+
.unwrap();
371+
}
372+
}
373+
374+
let _results: Vec<_> = accumulators
375+
.iter_mut()
376+
.map(|acc| acc.evaluate().unwrap())
377+
.collect();
378+
})
379+
});
380+
}
381+
}
382+
}
383+
}
384+
385+
// u32 benchmarks
386+
for num_groups in group_counts {
387+
for (card_name, distinct_pct) in cardinalities {
388+
for dist in distributions {
389+
let name = format!("u32_g{num_groups}_{card_name}_{dist}");
390+
let n_distinct = BATCH_SIZE * distinct_pct / 100;
391+
let values = Arc::new(create_u32_array(n_distinct)) as ArrayRef;
392+
let group_indices = if dist == "uniform" {
393+
create_uniform_groups(num_groups)
394+
} else {
395+
create_skewed_groups(num_groups)
396+
};
397+
398+
let (_schema, args) = prepare_args(DataType::UInt32);
399+
400+
if count_fn.groups_accumulator_supported(args.clone()) {
401+
c.bench_function(&format!("count_distinct_groups {name}"), |b| {
402+
b.iter(|| {
403+
let mut acc =
404+
count_fn.create_groups_accumulator(args.clone()).unwrap();
405+
acc.update_batch(
406+
std::slice::from_ref(&values),
407+
&group_indices,
408+
None,
409+
num_groups,
410+
)
411+
.unwrap();
412+
acc.evaluate(EmitTo::All).unwrap()
413+
})
414+
});
415+
} else {
416+
let arr = values.as_any().downcast_ref::<UInt32Array>().unwrap();
417+
let mut group_rows: Vec<Vec<u32>> = vec![Vec::new(); num_groups];
418+
for (idx, &group_idx) in group_indices.iter().enumerate() {
419+
if arr.is_valid(idx) {
420+
group_rows[group_idx].push(arr.value(idx));
421+
}
422+
}
423+
let group_arrays: Vec<ArrayRef> = group_rows
424+
.iter()
425+
.map(|rows| Arc::new(UInt32Array::from(rows.clone())) as ArrayRef)
426+
.collect();
427+
428+
c.bench_function(&format!("count_distinct_groups {name}"), |b| {
429+
b.iter(|| {
430+
let mut accumulators: Vec<_> = (0..num_groups)
431+
.map(|_| prepare_accumulator(DataType::UInt32))
432+
.collect();
433+
434+
for (group_idx, batch) in group_arrays.iter().enumerate() {
435+
if !batch.is_empty() {
436+
accumulators[group_idx]
437+
.update_batch(std::slice::from_ref(batch))
438+
.unwrap();
439+
}
440+
}
441+
442+
let _results: Vec<_> = accumulators
443+
.iter_mut()
444+
.map(|acc| acc.evaluate().unwrap())
445+
.collect();
446+
})
447+
});
448+
}
449+
}
450+
}
451+
}
151452
}
152453

153-
criterion_group!(benches, count_distinct_benchmark);
454+
criterion_group!(
455+
benches,
456+
count_distinct_benchmark,
457+
count_distinct_groups_benchmark
458+
);
154459
criterion_main!(benches);

0 commit comments

Comments
 (0)