Skip to content

Commit 36df145

Browse files
authored
feat: Add per-expression evaluation timing metrics to ProjectionExec (#19447)
## 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. --> Part of #18456 ## 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. --> See issue for the rationale, this PR is implementing the 1st part of the issue. Demo in `datafrusion-cli` ``` DataFusion CLI v51.0.0 > explain analyze select a+1, pow(a,2) from generate_series(1,1000000) as t1(a); +-------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | plan_type | plan | +-------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Plan with Metrics | ProjectionExec: expr=[a@0 + 1 as t1.a + Int64(1), power(CAST(a@0 AS Float64), 2) as pow(t1.a,Int64(2))], metrics=[output_rows=1.00 M, elapsed_compute=32.37ms, output_bytes=15.3 MB, output_batches=123, expr_eval_time_0=8.27ms, expr_eval_time_1=23.82ms] | | | RepartitionExec: partitioning=RoundRobinBatch(14), input_partitions=1, metrics=[output_rows=1.00 M, elapsed_compute=780.87µs, output_bytes=7.7 MB, output_batches=123, spill_count=0, spilled_bytes=0.0 B, spilled_rows=0, fetch_time=1.19ms, repartition_time=1ns, send_time=186.54µs] | | | ProjectionExec: expr=[value@0 as a], metrics=[output_rows=1.00 M, elapsed_compute=148.62µs, output_bytes=7.7 MB, output_batches=123, expr_eval_time_0=4.12µs] | | | LazyMemoryExec: partitions=1, batch_generators=[generate_series: start=1, end=1000000, batch_size=8192], metrics=[output_rows=1.00 M, elapsed_compute=1.01ms, output_bytes=7.7 MB, output_batches=123] | | | | +-------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row(s) fetched. ``` Each expressions' evaluation time are tracked individually in `expr_eval_time_*`. `expr_eval_time_0` is for `a+1`, and `expr_eval_time_1` is for `pow(a,2)`. I chose number index because the pretty formatting for expressions are still a bit verbose now (like `[a@0 + 1 as t1.a + Int64(1)`) ## 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. --> 1. Moved metrics module from `datafusion-execution` crate to `datafusion-physical-expr-common`. (I optimistically think it's enough to move to `execution` crate previously, however there are many execution utilities live in `physical-expr-common`, so we have to further move it down in the dependency tree) 2. Added a struct to hold each expression's evaluation time: `ExpressionEvaluatorMetrics` 3. Put `Option<ExpressionEvaluatorMetrics>` inside `Projector`, and change the execution accordingly. ## 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 4. 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)? --> Yes, added several slts ## 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. -->
1 parent 83ed192 commit 36df145

File tree

15 files changed

+213
-12
lines changed

15 files changed

+213
-12
lines changed

Cargo.lock

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

datafusion/execution/src/lib.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ pub mod cache;
3232
pub mod config;
3333
pub mod disk_manager;
3434
pub mod memory_pool;
35-
pub mod metrics;
3635
pub mod object_store;
3736
#[cfg(feature = "parquet_encryption")]
3837
pub mod parquet_encryption;

datafusion/physical-expr-common/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,9 @@ name = "datafusion_physical_expr_common"
4343
[dependencies]
4444
ahash = { workspace = true }
4545
arrow = { workspace = true }
46+
chrono = { workspace = true }
4647
datafusion-common = { workspace = true }
4748
datafusion-expr-common = { workspace = true }
4849
hashbrown = { workspace = true }
4950
itertools = { workspace = true }
51+
parking_lot = { workspace = true }

datafusion/physical-expr-common/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
pub mod binary_map;
3636
pub mod binary_view_map;
3737
pub mod datum;
38+
pub mod metrics;
3839
pub mod physical_expr;
3940
pub mod sort_expr;
4041
pub mod tree_node;

datafusion/execution/src/metrics/baseline.rs renamed to datafusion/physical-expr-common/src/metrics/baseline.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,9 @@ use super::{Count, ExecutionPlanMetricsSet, MetricBuilder, Time, Timestamp};
2929
///
3030
/// Example:
3131
/// ```
32-
/// use datafusion_execution::metrics::{BaselineMetrics, ExecutionPlanMetricsSet};
32+
/// use datafusion_physical_expr_common::metrics::{
33+
/// BaselineMetrics, ExecutionPlanMetricsSet,
34+
/// };
3335
/// let metrics = ExecutionPlanMetricsSet::new();
3436
///
3537
/// let partition = 2;

datafusion/execution/src/metrics/builder.rs renamed to datafusion/physical-expr-common/src/metrics/builder.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ use super::{
3434
/// case of constant strings
3535
///
3636
/// ```rust
37-
/// use datafusion_execution::metrics::*;
37+
/// use datafusion_physical_expr_common::metrics::*;
3838
///
3939
/// let metrics = ExecutionPlanMetricsSet::new();
4040
/// let partition = 1;

datafusion/execution/src/metrics/custom.rs renamed to datafusion/physical-expr-common/src/metrics/custom.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ use std::{any::Any, fmt::Debug, fmt::Display, sync::Arc};
4444
/// # use std::any::Any;
4545
/// # use std::sync::atomic::{AtomicUsize, Ordering};
4646
///
47-
/// # use datafusion_execution::metrics::CustomMetricValue;
47+
/// # use datafusion_physical_expr_common::metrics::CustomMetricValue;
4848
///
4949
/// #[derive(Debug, Default)]
5050
/// struct MyCounter {
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
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+
//! Metrics helpers for expression evaluation.
19+
20+
use super::{ExecutionPlanMetricsSet, MetricBuilder, MetricType, ScopedTimerGuard, Time};
21+
22+
/// Tracks evaluation time for a sequence of expressions.
23+
///
24+
/// # Example
25+
/// Given SQL query:
26+
/// EXPLAIN ANALYZE
27+
/// SELECT a+1, pow(a,2)
28+
/// FROM generate_series(1, 1000000) as t1(a)
29+
///
30+
/// This struct holds two time metrics for the projection expressions
31+
/// `a+1` and `pow(a,2)`, respectively.
32+
///
33+
/// The output reads:
34+
/// `ProjectionExec: expr=[a@0 + 1 as t1.a + Int64(1), power(CAST(a@0 AS Float64), 2) as pow(t1.a,Int64(2))], metrics=[... expr_0_eval_time=9.23ms, expr_1_eval_time=32.35ms...]`
35+
#[derive(Debug, Clone)]
36+
pub struct ExpressionEvaluatorMetrics {
37+
expression_times: Vec<Time>,
38+
}
39+
40+
impl ExpressionEvaluatorMetrics {
41+
/// Create metrics for a collection of expressions.
42+
///
43+
/// # Args
44+
/// - metrics: see `MetricBuilder` for details.
45+
/// - partition: see `MetricBuilder` for details.
46+
/// - expression_labels: unique identifier for each metric, so that the metric
47+
/// can get aggregated across multiple partitions. It is not the name showed
48+
/// in the `EXPLAIN ANALYZE`, the metric name will be `expr_{idx}_eval_time`
49+
/// according to the expression order.
50+
pub fn new<T>(
51+
metrics: &ExecutionPlanMetricsSet,
52+
partition: usize,
53+
expression_labels: impl IntoIterator<Item = T>,
54+
) -> Self
55+
where
56+
T: Into<String>,
57+
{
58+
let expression_times = expression_labels
59+
.into_iter()
60+
.enumerate()
61+
.map(|(idx, label)| {
62+
MetricBuilder::new(metrics)
63+
.with_new_label("expr", label.into())
64+
.with_type(MetricType::DEV)
65+
// Existing PhysicalExpr formatter is a bit verbose, so use simple name
66+
.subset_time(format!("expr_{idx}_eval_time"), partition)
67+
})
68+
.collect();
69+
70+
Self { expression_times }
71+
}
72+
73+
/// Returns a timer guard for the expression at `index`, if present.
74+
#[inline]
75+
pub fn scoped_timer(&self, index: usize) -> Option<ScopedTimerGuard<'_>> {
76+
self.expression_times.get(index).map(Time::timer)
77+
}
78+
79+
/// The number of tracked expressions.
80+
pub fn len(&self) -> usize {
81+
self.expression_times.len()
82+
}
83+
84+
/// True when no expressions are tracked.
85+
pub fn is_empty(&self) -> bool {
86+
self.expression_times.is_empty()
87+
}
88+
}

datafusion/execution/src/metrics/mod.rs renamed to datafusion/physical-expr-common/src/metrics/mod.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
mod baseline;
2121
mod builder;
2222
mod custom;
23+
mod expression;
2324
mod value;
2425

2526
use datafusion_common::HashMap;
@@ -35,6 +36,7 @@ use std::{
3536
pub use baseline::{BaselineMetrics, RecordOutput, SpillMetrics, SplitMetrics};
3637
pub use builder::MetricBuilder;
3738
pub use custom::CustomMetricValue;
39+
pub use expression::ExpressionEvaluatorMetrics;
3840
pub use value::{
3941
Count, Gauge, MetricValue, PruningMetrics, RatioMergeStrategy, RatioMetrics,
4042
ScopedTimerGuard, Time, Timestamp,
@@ -47,7 +49,7 @@ pub use value::{
4749
/// [`ExecutionPlanMetricsSet`].
4850
///
4951
/// ```
50-
/// use datafusion_execution::metrics::*;
52+
/// use datafusion_physical_expr_common::metrics::*;
5153
///
5254
/// let metrics = ExecutionPlanMetricsSet::new();
5355
/// assert!(metrics.clone_inner().output_rows().is_none());
File renamed without changes.

0 commit comments

Comments
 (0)