Skip to content

Apache DataFusion SQL Query Engine

Add parquet-filter and sort benchmarks to dfbench (#7120)

Andrew Lamb2ec0bc106540
diff --git a/benchmarks/README.md b/benchmarks/README.md
index 99b432a387..c0baa43ab8 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -229,31 +229,14 @@ This will produce output like
└──────────────┴──────────────┴──────────────┴───────────────┘
```
-### Expected output
+# Benchmark Runner
-The result of query 1 should produce the following output when executed against the SF=1 dataset.
+The `dfbench` program contains subcommands to run the various
+benchmarks. When benchmarking, it should always be built in release
+mode using `--release`.
-```
-+--------------+--------------+----------+--------------------+--------------------+--------------------+--------------------+--------------------+----------------------+-------------+
-| l_returnflag | l_linestatus | sum_qty | sum_base_price | sum_disc_price | sum_charge | avg_qty | avg_price | avg_disc | count_order |
-+--------------+--------------+----------+--------------------+--------------------+--------------------+--------------------+--------------------+----------------------+-------------+
-| A | F | 37734107 | 56586554400.73001 | 53758257134.870026 | 55909065222.82768 | 25.522005853257337 | 38273.12973462168 | 0.049985295838396455 | 1478493 |
-| N | F | 991417 | 1487504710.3799996 | 1413082168.0541 | 1469649223.1943746 | 25.516471920522985 | 38284.467760848296 | 0.05009342667421622 | 38854 |
-| N | O | 74476023 | 111701708529.50996 | 106118209986.10472 | 110367023144.56622 | 25.502229680934594 | 38249.1238377803 | 0.049996589476752576 | 2920373 |
-| R | F | 37719753 | 56568041380.90001 | 53741292684.60399 | 55889619119.83194 | 25.50579361269077 | 38250.854626099666 | 0.05000940583012587 | 1478870 |
-+--------------+--------------+----------+--------------------+--------------------+--------------------+--------------------+--------------------+----------------------+-------------+
-Query 1 iteration 0 took 1956.1 ms
-Query 1 avg time: 1956.11 ms
-```
-
-# Benchmark Descriptions
-
-## `dfbench`
-
-The `dfbench` program contains subcommands to run various benchmarks.
-
-Full help can be found in the relevant sub command. For example to get help for tpch,
-run `cargo run --release --bin dfbench tpch --help`
+Full help for each benchmark can be found in the relevant sub
+command. For example to get help for tpch, run
```shell
cargo run --release --bin dfbench --help
@@ -265,61 +248,52 @@ USAGE:
dfbench <SUBCOMMAND>
SUBCOMMANDS:
- clickbench Run the clickbench benchmark
- help Prints this message or the help of the given subcommand(s)
- tpch Run the tpch benchmark.
- tpch-convert Convert tpch .slt files to .parquet or .csv files
+ clickbench Run the clickbench benchmark
+ help Prints this message or the help of the given subcommand(s)
+ parquet-filter Test performance of parquet filter pushdown
+ sort Test performance of parquet filter pushdown
+ tpch Run the tpch benchmark.
+ tpch-convert Convert tpch .slt files to .parquet or .csv files
```
-## h2o benchmarks
+# Benchmarks
-```bash
-cargo run --release --bin h2o group-by --query 1 --path /mnt/bigdata/h2oai/N_1e7_K_1e2_single.csv --mem-table --debug
-```
+The output of `dfbench` help includes a descripion of each benchmark, which is reproducedd here for convenience
-Example run:
+## ClickBench
-```
-Running benchmarks with the following options: GroupBy(GroupBy { query: 1, path: "/mnt/bigdata/h2oai/N_1e7_K_1e2_single.csv", debug: false })
-Executing select id1, sum(v1) as v1 from x group by id1
-+-------+--------+
-| id1 | v1 |
-+-------+--------+
-| id063 | 199420 |
-| id094 | 200127 |
-| id044 | 198886 |
-...
-| id093 | 200132 |
-| id003 | 199047 |
-+-------+--------+
+The ClickBench[1] benchmarks are widely cited in the industry and
+focus on grouping / aggregation / filtering. This runner uses the
+scripts and queries from [2].
-h2o groupby query 1 took 1669 ms
-```
+[1]: https://github.com/ClickHouse/ClickBench
+[2]: https://github.com/ClickHouse/ClickBench/tree/main/datafusion
-[1]: http://www.tpc.org/tpch/
-[2]: https://www1.nyc.gov/site/tlc/about/tlc-trip-record-data.page
+## Parquet Filter
-## Parquet benchmarks
+Test performance of parquet filter pushdown
-This is a set of benchmarks for testing and verifying performance of parquet filtering and sorting.
-The queries are executed on a synthetic dataset generated during the benchmark execution and designed to simulate web server access logs.
+The queries are executed on a synthetic dataset generated during
+the benchmark execution and designed to simulate web server access
+logs.
-To run filter benchmarks, run:
+Example
-```base
-cargo run --release --bin parquet -- filter --path ./data --scale-factor 1.0
-```
+dfbench parquet-filter --path ./data --scale-factor 1.0
-This will generate the synthetic dataset at `./data/logs.parquet`. The size of the dataset can be controlled through the `size_factor`
+generates the synthetic dataset at `./data/logs.parquet`. The size
+of the dataset can be controlled through the `size_factor`
(with the default value of `1.0` generating a ~1GB parquet file).
-For each filter we will run the query using different `ParquetScanOption` settings.
+For each filter we will run the query using different
+`ParquetScanOption` settings.
-Example run:
+Example output:
```
-Running benchmarks with the following options: Opt { debug: false, iterations: 3, partitions: 2, path: "./data", batch_size: 8192, scale_factor: 1.0 }
+Running benchmarks with the following options: Opt { debug: false, iterations: 3, partitions: 2, path: "./data",
+batch_size: 8192, scale_factor: 1.0 }
Generated test dataset with 10699521 rows
Executing with filter 'request_method = Utf8("GET")'
Using scan options ParquetScanOptions { pushdown_filters: false, reorder_predicates: false, enable_page_index: false }
@@ -337,12 +311,56 @@ Iteration 2 returned 1781686 rows in 1947 ms
...
```
-Similarly, to run sorting benchmarks, run:
+## Sort
+Test performance of sorting large datasets
+
+This test sorts a a synthetic dataset generated during the
+benchmark execution, designed to simulate sorting web server
+access logs. Such sorting is often done during data transformation
+steps.
+
+The tests sort the entire dataset using several different sort
+orders.
+
+## TPCH
+
+Run the tpch benchmark.
+
+This benchmarks is derived from the [TPC-H][1] version
+[2.17.1]. The data and answers are generated using `tpch-gen` from
+[2].
+
+[1]: http://www.tpc.org/tpch/
+[2]: https://github.com/databricks/tpch-dbgen.git,
+[2.17.1]: https://www.tpc.org/tpc_documents_current_versions/pdf/tpc-h_v2.17.1.pdf
+
+
+# Older Benchmarks
+
+## h2o benchmarks
+
+```bash
+cargo run --release --bin h2o group-by --query 1 --path /mnt/bigdata/h2oai/N_1e7_K_1e2_single.csv --mem-table --debug
+```
+
+Example run:
+
+```
+Running benchmarks with the following options: GroupBy(GroupBy { query: 1, path: "/mnt/bigdata/h2oai/N_1e7_K_1e2_single.csv", debug: false })
+Executing select id1, sum(v1) as v1 from x group by id1
++-------+--------+
+| id1 | v1 |
++-------+--------+
+| id063 | 199420 |
+| id094 | 200127 |
+| id044 | 198886 |
+...
+| id093 | 200132 |
+| id003 | 199047 |
++-------+--------+
-```base
-cargo run --release --bin parquet -- sort --path ./data --scale-factor 1.0
+h2o groupby query 1 took 1669 ms
```
-This proceeds in the same way as the filter benchmarks: each sort expression
-combination will be run using the same set of `ParquetScanOption` as the
-filter benchmarks.
+[1]: http://www.tpc.org/tpch/
+[2]: https://www1.nyc.gov/site/tlc/about/tlc-trip-record-data.page
diff --git a/benchmarks/bench.sh b/benchmarks/bench.sh
index f50640f6fc..bdbdc0e517 100755
--- a/benchmarks/bench.sh
+++ b/benchmarks/bench.sh
@@ -182,6 +182,7 @@ main() {
# navigate to the appropriate directory
pushd "${DATAFUSION_DIR}/benchmarks" > /dev/null
mkdir -p "${RESULTS_DIR}"
+ mkdir -p "${DATA_DIR}"
case "$BENCHMARK" in
all)
run_tpch "1"
diff --git a/benchmarks/src/bin/dfbench.rs b/benchmarks/src/bin/dfbench.rs
index d5a17a2ab5..441b6cdc02 100644
--- a/benchmarks/src/bin/dfbench.rs
+++ b/benchmarks/src/bin/dfbench.rs
@@ -28,7 +28,7 @@ static ALLOC: snmalloc_rs::SnMalloc = snmalloc_rs::SnMalloc;
#[global_allocator]
static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc;
-use datafusion_benchmarks::{clickbench, tpch};
+use datafusion_benchmarks::{clickbench, parquet_filter, sort, tpch};
#[derive(Debug, StructOpt)]
#[structopt(about = "benchmark command")]
@@ -36,6 +36,8 @@ enum Options {
Tpch(tpch::RunOpt),
TpchConvert(tpch::ConvertOpt),
Clickbench(clickbench::RunOpt),
+ ParquetFilter(parquet_filter::RunOpt),
+ Sort(sort::RunOpt),
}
// Main benchmark runner entrypoint
@@ -47,5 +49,7 @@ pub async fn main() -> Result<()> {
Options::Tpch(opt) => opt.run().await,
Options::TpchConvert(opt) => opt.run().await,
Options::Clickbench(opt) => opt.run().await,
+ Options::ParquetFilter(opt) => opt.run().await,
+ Options::Sort(opt) => opt.run().await,
}
}
diff --git a/benchmarks/src/bin/parquet.rs b/benchmarks/src/bin/parquet.rs
index 98b2da7c2f..18871803fc 100644
--- a/benchmarks/src/bin/parquet.rs
+++ b/benchmarks/src/bin/parquet.rs
@@ -15,22 +15,10 @@
// specific language governing permissions and limitations
// under the License.
-use arrow::util::pretty;
use datafusion::common::Result;
-use datafusion::logical_expr::{lit, or, Expr};
-use datafusion::optimizer::utils::disjunction;
-use datafusion::physical_expr::PhysicalSortExpr;
-use datafusion::physical_plan::collect;
-use datafusion::physical_plan::sorts::sort::SortExec;
-use datafusion::prelude::{col, SessionConfig, SessionContext};
-use datafusion::test_util::parquet::{ParquetScanOptions, TestParquetFile};
-use datafusion_benchmarks::BenchmarkRun;
-use parquet::file::properties::WriterProperties;
-use std::path::PathBuf;
-use std::sync::Arc;
-use std::time::Instant;
+
+use datafusion_benchmarks::{parquet_filter, sort};
use structopt::StructOpt;
-use test_utils::AccessLogGenerator;
#[cfg(feature = "snmalloc")]
#[global_allocator]
@@ -40,63 +28,9 @@ static ALLOC: snmalloc_rs::SnMalloc = snmalloc_rs::SnMalloc;
#[structopt(name = "Benchmarks", about = "Apache Arrow Rust Benchmarks.")]
enum ParquetBenchCmd {
/// Benchmark sorting parquet files
- Sort(Opt),
+ Sort(sort::RunOpt),
/// Benchmark parquet filter pushdown
- Filter(Opt),
-}
-
-#[derive(Debug, StructOpt, Clone)]
-struct Opt {
- /// Activate debug mode to see query results
- #[structopt(short, long)]
- debug: bool,
-
- /// Number of iterations of each test run
- #[structopt(short = "i", long = "iterations", default_value = "3")]
- iterations: usize,
-
- /// Number of partitions to process in parallel
- #[structopt(long = "partitions", default_value = "2")]
- partitions: usize,
-
- /// Path to folder where access log file will be generated
- #[structopt(parse(from_os_str), required = true, short = "p", long = "path")]
- path: PathBuf,
- /// Data page size of the generated parquet file
- #[structopt(long = "page-size")]
- page_size: Option<usize>,
-
- /// Data page size of the generated parquet file
- #[structopt(long = "row-group-size")]
- row_group_size: Option<usize>,
-
- /// Total size of generated dataset. The default scale factor of 1.0 will generate a roughly 1GB parquet file
- #[structopt(short = "s", long = "scale-factor", default_value = "1.0")]
- scale_factor: f32,
-
- /// Path to machine readable output file
- #[structopt(parse(from_os_str), short = "o", long = "output")]
- output_path: Option<PathBuf>,
-}
-impl Opt {
- /// Initialize parquet test file given options.
- fn init_file(&self) -> Result<TestParquetFile> {
- let path = self.path.join("logs.parquet");
-
- let mut props_builder = WriterProperties::builder();
-
- if let Some(s) = self.page_size {
- props_builder = props_builder
- .set_data_page_size_limit(s)
- .set_write_batch_size(s);
- }
-
- if let Some(s) = self.row_group_size {
- props_builder = props_builder.set_max_row_group_size(s);
- }
-
- gen_data(path, self.scale_factor, props_builder.build())
- }
+ Filter(parquet_filter::RunOpt),
}
#[tokio::main]
@@ -105,245 +39,11 @@ async fn main() -> Result<()> {
match cmd {
ParquetBenchCmd::Filter(opt) => {
println!("running filter benchmarks");
- let test_file = opt.init_file()?;
- run_filter_benchmarks(opt, &test_file).await?;
+ opt.run().await
}
ParquetBenchCmd::Sort(opt) => {
println!("running sort benchmarks");
- let test_file = opt.init_file()?;
- run_sort_benchmarks(opt, &test_file).await?;
- }
- }
- Ok(())
-}
-
-async fn run_sort_benchmarks(opt: Opt, test_file: &TestParquetFile) -> Result<()> {
- use datafusion::physical_expr::expressions::col;
- let mut rundata = BenchmarkRun::new();
- let schema = test_file.schema();
- let sort_cases = vec![
- (
- "sort utf8",
- vec![PhysicalSortExpr {
- expr: col("request_method", &schema)?,
- options: Default::default(),
- }],
- ),
- (
- "sort int",
- vec![PhysicalSortExpr {
- expr: col("request_bytes", &schema)?,
- options: Default::default(),
- }],
- ),
- (
- "sort decimal",
- vec![
- // sort decimal
- PhysicalSortExpr {
- expr: col("decimal_price", &schema)?,
- options: Default::default(),
- },
- ],
- ),
- (
- "sort integer tuple",
- vec![
- PhysicalSortExpr {
- expr: col("request_bytes", &schema)?,
- options: Default::default(),
- },
- PhysicalSortExpr {
- expr: col("response_bytes", &schema)?,
- options: Default::default(),
- },
- ],
- ),
- (
- "sort utf8 tuple",
- vec![
- // sort utf8 tuple
- PhysicalSortExpr {
- expr: col("service", &schema)?,
- options: Default::default(),
- },
- PhysicalSortExpr {
- expr: col("host", &schema)?,
- options: Default::default(),
- },
- PhysicalSortExpr {
- expr: col("pod", &schema)?,
- options: Default::default(),
- },
- PhysicalSortExpr {
- expr: col("image", &schema)?,
- options: Default::default(),
- },
- ],
- ),
- (
- "sort mixed tuple",
- vec![
- PhysicalSortExpr {
- expr: col("service", &schema)?,
- options: Default::default(),
- },
- PhysicalSortExpr {
- expr: col("request_bytes", &schema)?,
- options: Default::default(),
- },
- PhysicalSortExpr {
- expr: col("decimal_price", &schema)?,
- options: Default::default(),
- },
- ],
- ),
- ];
- for (title, expr) in sort_cases {
- println!("Executing '{title}' (sorting by: {expr:?})");
- rundata.start_new_case(title);
- for i in 0..opt.iterations {
- let config = SessionConfig::new().with_target_partitions(opt.partitions);
- let ctx = SessionContext::with_config(config);
- let (rows, elapsed) = exec_sort(&ctx, &expr, test_file, opt.debug).await?;
- let ms = elapsed.as_secs_f64() * 1000.0;
- println!("Iteration {i} finished in {ms} ms");
- rundata.write_iter(elapsed, rows);
- }
- println!("\n");
- }
- if let Some(path) = &opt.output_path {
- std::fs::write(path, rundata.to_json())?;
- }
- Ok(())
-}
-fn parquet_scan_disp(opts: &ParquetScanOptions) -> String {
- format!(
- "pushdown_filters={}, reorder_filters={}, page_index={}",
- opts.pushdown_filters, opts.reorder_filters, opts.enable_page_index
- )
-}
-async fn run_filter_benchmarks(opt: Opt, test_file: &TestParquetFile) -> Result<()> {
- let mut rundata = BenchmarkRun::new();
- let scan_options_matrix = vec![
- ParquetScanOptions {
- pushdown_filters: false,
- reorder_filters: false,
- enable_page_index: false,
- },
- ParquetScanOptions {
- pushdown_filters: true,
- reorder_filters: true,
- enable_page_index: true,
- },
- ParquetScanOptions {
- pushdown_filters: true,
- reorder_filters: true,
- enable_page_index: false,
- },
- ];
-
- let filter_matrix = vec![
- ("Selective-ish filter", col("request_method").eq(lit("GET"))),
- (
- "Non-selective filter",
- col("request_method").not_eq(lit("GET")),
- ),
- (
- "Basic conjunction",
- col("request_method")
- .eq(lit("POST"))
- .and(col("response_status").eq(lit(503_u16))),
- ),
- (
- "Nested filters",
- col("request_method").eq(lit("POST")).and(or(
- col("response_status").eq(lit(503_u16)),
- col("response_status").eq(lit(403_u16)),
- )),
- ),
- (
- "Many filters",
- disjunction([
- col("request_method").not_eq(lit("GET")),
- col("response_status").eq(lit(400_u16)),
- col("service").eq(lit("backend")),
- ])
- .unwrap(),
- ),
- ("Filter everything", col("response_status").eq(lit(429_u16))),
- ("Filter nothing", col("response_status").gt(lit(0_u16))),
- ];
-
- for (name, filter_expr) in &filter_matrix {
- println!("Executing '{name}' (filter: {filter_expr})");
- for scan_options in &scan_options_matrix {
- println!("Using scan options {scan_options:?}");
- rundata
- .start_new_case(&format!("{name}: {}", parquet_scan_disp(scan_options)));
- for i in 0..opt.iterations {
- let config = scan_options.config().with_target_partitions(opt.partitions);
- let ctx = SessionContext::with_config(config);
-
- let (rows, elapsed) =
- exec_scan(&ctx, test_file, filter_expr.clone(), opt.debug).await?;
- let ms = elapsed.as_secs_f64() * 1000.0;
- println!("Iteration {i} returned {rows} rows in {ms} ms");
- rundata.write_iter(elapsed, rows);
- }
+ opt.run().await
}
- println!("\n");
- }
- rundata.maybe_write_json(opt.output_path.as_ref())?;
- Ok(())
-}
-
-async fn exec_scan(
- ctx: &SessionContext,
- test_file: &TestParquetFile,
- filter: Expr,
- debug: bool,
-) -> Result<(usize, std::time::Duration)> {
- let start = Instant::now();
- let exec = test_file.create_scan(Some(filter)).await?;
-
- let task_ctx = ctx.task_ctx();
- let result = collect(exec, task_ctx).await?;
- let elapsed = start.elapsed();
- if debug {
- pretty::print_batches(&result)?;
- }
- let rows = result.iter().map(|b| b.num_rows()).sum();
- Ok((rows, elapsed))
-}
-
-async fn exec_sort(
- ctx: &SessionContext,
- expr: &[PhysicalSortExpr],
- test_file: &TestParquetFile,
- debug: bool,
-) -> Result<(usize, std::time::Duration)> {
- let start = Instant::now();
- let scan = test_file.create_scan(None).await?;
- let exec = Arc::new(SortExec::new(expr.to_owned(), scan));
- let task_ctx = ctx.task_ctx();
- let result = collect(exec, task_ctx).await?;
- let elapsed = start.elapsed();
- if debug {
- pretty::print_batches(&result)?;
}
- let rows = result.iter().map(|b| b.num_rows()).sum();
- Ok((rows, elapsed))
-}
-
-fn gen_data(
- path: PathBuf,
- scale_factor: f32,
- props: WriterProperties,
-) -> Result<TestParquetFile> {
- let generator = AccessLogGenerator::new();
-
- let num_batches = 100_f32 * scale_factor;
-
- TestParquetFile::try_new(path, props, generator.take(num_batches as usize))
}
diff --git a/benchmarks/src/clickbench.rs b/benchmarks/src/clickbench.rs
index c884af8094..e5cdd356fe 100644
--- a/benchmarks/src/clickbench.rs
+++ b/benchmarks/src/clickbench.rs
@@ -83,7 +83,7 @@ impl RunOpt {
let ctx = SessionContext::with_config(config);
self.register_hits(&ctx).await?;
- let iterations = self.common.iterations();
+ let iterations = self.common.iterations;
let mut benchmark_run = BenchmarkRun::new();
for query_id in query_range {
benchmark_run.start_new_case(&format!("Query {query_id}"));
diff --git a/benchmarks/src/lib.rs b/benchmarks/src/lib.rs
index 8cab151115..f81220aa2c 100644
--- a/benchmarks/src/lib.rs
+++ b/benchmarks/src/lib.rs
@@ -17,9 +17,8 @@
//! DataFusion benchmark runner
pub mod clickbench;
+pub mod parquet_filter;
+pub mod sort;
pub mod tpch;
-
-mod options;
-mod run;
-pub use options::CommonOpt;
-pub use run::{BenchQuery, BenchmarkRun};
+mod util;
+pub use util::*;
diff --git a/benchmarks/src/parquet_filter.rs b/benchmarks/src/parquet_filter.rs
new file mode 100644
index 0000000000..ceea12de92
--- /dev/null
+++ b/benchmarks/src/parquet_filter.rs
@@ -0,0 +1,192 @@
+// 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 crate::AccessLogOpt;
+use crate::{BenchmarkRun, CommonOpt};
+use arrow::util::pretty;
+use datafusion::common::Result;
+use datafusion::logical_expr::{lit, or, Expr};
+use datafusion::optimizer::utils::disjunction;
+use datafusion::physical_plan::collect;
+use datafusion::prelude::{col, SessionContext};
+use datafusion::test_util::parquet::{ParquetScanOptions, TestParquetFile};
+use std::path::PathBuf;
+use std::time::Instant;
+use structopt::StructOpt;
+
+/// Test performance of parquet filter pushdown
+///
+/// The queries are executed on a synthetic dataset generated during
+/// the benchmark execution and designed to simulate web server access
+/// logs.
+///
+/// Example
+///
+/// dfbench parquet-filter --path ./data --scale-factor 1.0
+///
+/// generates the synthetic dataset at `./data/logs.parquet`. The size
+/// of the dataset can be controlled through the `size_factor`
+/// (with the default value of `1.0` generating a ~1GB parquet file).
+///
+/// For each filter we will run the query using different
+/// `ParquetScanOption` settings.
+///
+/// Example output:
+///
+/// Running benchmarks with the following options: Opt { debug: false, iterations: 3, partitions: 2, path: "./data", batch_size: 8192, scale_factor: 1.0 }
+/// Generated test dataset with 10699521 rows
+/// Executing with filter 'request_method = Utf8("GET")'
+/// Using scan options ParquetScanOptions { pushdown_filters: false, reorder_predicates: false, enable_page_index: false }
+/// Iteration 0 returned 10699521 rows in 1303 ms
+/// Iteration 1 returned 10699521 rows in 1288 ms
+/// Iteration 2 returned 10699521 rows in 1266 ms
+/// Using scan options ParquetScanOptions { pushdown_filters: true, reorder_predicates: true, enable_page_index: true }
+/// Iteration 0 returned 1781686 rows in 1970 ms
+/// Iteration 1 returned 1781686 rows in 2002 ms
+/// Iteration 2 returned 1781686 rows in 1988 ms
+/// Using scan options ParquetScanOptions { pushdown_filters: true, reorder_predicates: false, enable_page_index: true }
+/// Iteration 0 returned 1781686 rows in 1940 ms
+/// Iteration 1 returned 1781686 rows in 1986 ms
+/// Iteration 2 returned 1781686 rows in 1947 ms
+/// ...
+#[derive(Debug, StructOpt, Clone)]
+#[structopt(verbatim_doc_comment)]
+pub struct RunOpt {
+ /// Common options
+ #[structopt(flatten)]
+ common: CommonOpt,
+
+ /// Create data files
+ #[structopt(flatten)]
+ access_log: AccessLogOpt,
+
+ /// Path to machine readable output file
+ #[structopt(parse(from_os_str), short = "o", long = "output")]
+ output_path: Option<PathBuf>,
+}
+
+impl RunOpt {
+ pub async fn run(self) -> Result<()> {
+ let test_file = self.access_log.build()?;
+
+ let mut rundata = BenchmarkRun::new();
+ let scan_options_matrix = vec![
+ ParquetScanOptions {
+ pushdown_filters: false,
+ reorder_filters: false,
+ enable_page_index: false,
+ },
+ ParquetScanOptions {
+ pushdown_filters: true,
+ reorder_filters: true,
+ enable_page_index: true,
+ },
+ ParquetScanOptions {
+ pushdown_filters: true,
+ reorder_filters: true,
+ enable_page_index: false,
+ },
+ ];
+
+ let filter_matrix = vec![
+ ("Selective-ish filter", col("request_method").eq(lit("GET"))),
+ (
+ "Non-selective filter",
+ col("request_method").not_eq(lit("GET")),
+ ),
+ (
+ "Basic conjunction",
+ col("request_method")
+ .eq(lit("POST"))
+ .and(col("response_status").eq(lit(503_u16))),
+ ),
+ (
+ "Nested filters",
+ col("request_method").eq(lit("POST")).and(or(
+ col("response_status").eq(lit(503_u16)),
+ col("response_status").eq(lit(403_u16)),
+ )),
+ ),
+ (
+ "Many filters",
+ disjunction([
+ col("request_method").not_eq(lit("GET")),
+ col("response_status").eq(lit(400_u16)),
+ col("service").eq(lit("backend")),
+ ])
+ .unwrap(),
+ ),
+ ("Filter everything", col("response_status").eq(lit(429_u16))),
+ ("Filter nothing", col("response_status").gt(lit(0_u16))),
+ ];
+
+ for (name, filter_expr) in &filter_matrix {
+ println!("Executing '{name}' (filter: {filter_expr})");
+ for scan_options in &scan_options_matrix {
+ println!("Using scan options {scan_options:?}");
+ rundata.start_new_case(&format!(
+ "{name}: {}",
+ parquet_scan_disp(scan_options)
+ ));
+ for i in 0..self.common.iterations {
+ let config = self.common.update_config(scan_options.config());
+ let ctx = SessionContext::with_config(config);
+
+ let (rows, elapsed) = exec_scan(
+ &ctx,
+ &test_file,
+ filter_expr.clone(),
+ self.common.debug,
+ )
+ .await?;
+ let ms = elapsed.as_secs_f64() * 1000.0;
+ println!("Iteration {i} returned {rows} rows in {ms} ms");
+ rundata.write_iter(elapsed, rows);
+ }
+ }
+ println!("\n");
+ }
+ rundata.maybe_write_json(self.output_path.as_ref())?;
+ Ok(())
+ }
+}
+
+fn parquet_scan_disp(opts: &ParquetScanOptions) -> String {
+ format!(
+ "pushdown_filters={}, reorder_filters={}, page_index={}",
+ opts.pushdown_filters, opts.reorder_filters, opts.enable_page_index
+ )
+}
+
+async fn exec_scan(
+ ctx: &SessionContext,
+ test_file: &TestParquetFile,
+ filter: Expr,
+ debug: bool,
+) -> Result<(usize, std::time::Duration)> {
+ let start = Instant::now();
+ let exec = test_file.create_scan(Some(filter)).await?;
+
+ let task_ctx = ctx.task_ctx();
+ let result = collect(exec, task_ctx).await?;
+ let elapsed = start.elapsed();
+ if debug {
+ pretty::print_batches(&result)?;
+ }
+ let rows = result.iter().map(|b| b.num_rows()).sum();
+ Ok((rows, elapsed))
+}
diff --git a/benchmarks/src/sort.rs b/benchmarks/src/sort.rs
new file mode 100644
index 0000000000..d1baae8687
--- /dev/null
+++ b/benchmarks/src/sort.rs
@@ -0,0 +1,186 @@
+// 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 crate::AccessLogOpt;
+use crate::BenchmarkRun;
+use crate::CommonOpt;
+use arrow::util::pretty;
+use datafusion::common::Result;
+use datafusion::physical_expr::PhysicalSortExpr;
+use datafusion::physical_plan::collect;
+use datafusion::physical_plan::sorts::sort::SortExec;
+use datafusion::prelude::{SessionConfig, SessionContext};
+use datafusion::test_util::parquet::TestParquetFile;
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::time::Instant;
+use structopt::StructOpt;
+
+/// Test performance of sorting large datasets
+///
+/// This test sorts a a synthetic dataset generated during the
+/// benchmark execution, designed to simulate sorting web server
+/// access logs. Such sorting is often done during data transformation
+/// steps.
+///
+/// The tests sort the entire dataset using several different sort
+/// orders.
+///
+/// Example:
+///
+/// dfbench sort --path ./data --scale-factor 1.0
+#[derive(Debug, StructOpt, Clone)]
+#[structopt(verbatim_doc_comment)]
+pub struct RunOpt {
+ /// Common options
+ #[structopt(flatten)]
+ common: CommonOpt,
+
+ /// Create data files
+ #[structopt(flatten)]
+ access_log: AccessLogOpt,
+
+ /// Path to machine readable output file
+ #[structopt(parse(from_os_str), short = "o", long = "output")]
+ output_path: Option<PathBuf>,
+}
+
+impl RunOpt {
+ pub async fn run(self) -> Result<()> {
+ let test_file = self.access_log.build()?;
+
+ use datafusion::physical_expr::expressions::col;
+ let mut rundata = BenchmarkRun::new();
+ let schema = test_file.schema();
+ let sort_cases = vec![
+ (
+ "sort utf8",
+ vec![PhysicalSortExpr {
+ expr: col("request_method", &schema)?,
+ options: Default::default(),
+ }],
+ ),
+ (
+ "sort int",
+ vec![PhysicalSortExpr {
+ expr: col("request_bytes", &schema)?,
+ options: Default::default(),
+ }],
+ ),
+ (
+ "sort decimal",
+ vec![
+ // sort decimal
+ PhysicalSortExpr {
+ expr: col("decimal_price", &schema)?,
+ options: Default::default(),
+ },
+ ],
+ ),
+ (
+ "sort integer tuple",
+ vec![
+ PhysicalSortExpr {
+ expr: col("request_bytes", &schema)?,
+ options: Default::default(),
+ },
+ PhysicalSortExpr {
+ expr: col("response_bytes", &schema)?,
+ options: Default::default(),
+ },
+ ],
+ ),
+ (
+ "sort utf8 tuple",
+ vec![
+ // sort utf8 tuple
+ PhysicalSortExpr {
+ expr: col("service", &schema)?,
+ options: Default::default(),
+ },
+ PhysicalSortExpr {
+ expr: col("host", &schema)?,
+ options: Default::default(),
+ },
+ PhysicalSortExpr {
+ expr: col("pod", &schema)?,
+ options: Default::default(),
+ },
+ PhysicalSortExpr {
+ expr: col("image", &schema)?,
+ options: Default::default(),
+ },
+ ],
+ ),
+ (
+ "sort mixed tuple",
+ vec![
+ PhysicalSortExpr {
+ expr: col("service", &schema)?,
+ options: Default::default(),
+ },
+ PhysicalSortExpr {
+ expr: col("request_bytes", &schema)?,
+ options: Default::default(),
+ },
+ PhysicalSortExpr {
+ expr: col("decimal_price", &schema)?,
+ options: Default::default(),
+ },
+ ],
+ ),
+ ];
+ for (title, expr) in sort_cases {
+ println!("Executing '{title}' (sorting by: {expr:?})");
+ rundata.start_new_case(title);
+ for i in 0..self.common.iterations {
+ let config =
+ SessionConfig::new().with_target_partitions(self.common.partitions);
+ let ctx = SessionContext::with_config(config);
+ let (rows, elapsed) =
+ exec_sort(&ctx, &expr, &test_file, self.common.debug).await?;
+ let ms = elapsed.as_secs_f64() * 1000.0;
+ println!("Iteration {i} finished in {ms} ms");
+ rundata.write_iter(elapsed, rows);
+ }
+ println!("\n");
+ }
+ if let Some(path) = &self.output_path {
+ std::fs::write(path, rundata.to_json())?;
+ }
+ Ok(())
+ }
+}
+
+async fn exec_sort(
+ ctx: &SessionContext,
+ expr: &[PhysicalSortExpr],
+ test_file: &TestParquetFile,
+ debug: bool,
+) -> Result<(usize, std::time::Duration)> {
+ let start = Instant::now();
+ let scan = test_file.create_scan(None).await?;
+ let exec = Arc::new(SortExec::new(expr.to_owned(), scan));
+ let task_ctx = ctx.task_ctx();
+ let result = collect(exec, task_ctx).await?;
+ let elapsed = start.elapsed();
+ if debug {
+ pretty::print_batches(&result)?;
+ }
+ let rows = result.iter().map(|b| b.num_rows()).sum();
+ Ok((rows, elapsed))
+}
diff --git a/benchmarks/src/tpch/run.rs b/benchmarks/src/tpch/run.rs
index 5b43f2b93f..9817c37cef 100644
--- a/benchmarks/src/tpch/run.rs
+++ b/benchmarks/src/tpch/run.rs
@@ -58,10 +58,6 @@ pub struct RunOpt {
#[structopt(short, long)]
query: Option<usize>,
- /// Activate debug mode to see query results
- #[structopt(short, long)]
- debug: bool,
-
/// Common options
#[structopt(flatten)]
common: CommonOpt,
@@ -190,7 +186,7 @@ impl RunOpt {
ctx: &SessionContext,
sql: &str,
) -> Result<Vec<RecordBatch>> {
- let debug = self.debug;
+ let debug = self.common.debug;
let plan = ctx.sql(sql).await?;
let (state, plan) = plan.into_parts();
@@ -286,11 +282,11 @@ impl RunOpt {
}
fn iterations(&self) -> usize {
- self.common.iterations()
+ self.common.iterations
}
fn partitions(&self) -> usize {
- self.common.partitions()
+ self.common.partitions
}
}
@@ -331,10 +327,10 @@ mod tests {
iterations: 1,
partitions: 2,
batch_size: 8192,
+ debug: false,
};
let opt = RunOpt {
query: Some(query),
- debug: false,
common,
path: PathBuf::from(path.to_string()),
file_format: "tbl".to_string(),
@@ -363,10 +359,10 @@ mod tests {
iterations: 1,
partitions: 2,
batch_size: 8192,
+ debug: false,
};
let opt = RunOpt {
query: Some(query),
- debug: false,
common,
path: PathBuf::from(path.to_string()),
file_format: "tbl".to_string(),
diff --git a/benchmarks/src/util/access_log.rs b/benchmarks/src/util/access_log.rs
new file mode 100644
index 0000000000..2b29465ee2
--- /dev/null
+++ b/benchmarks/src/util/access_log.rs
@@ -0,0 +1,74 @@
+// 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.
+
+//! Benchmark data generation
+
+use datafusion::common::Result;
+use datafusion::test_util::parquet::TestParquetFile;
+use parquet::file::properties::WriterProperties;
+use std::path::PathBuf;
+use structopt::StructOpt;
+use test_utils::AccessLogGenerator;
+
+// Options and builder for making an access log test file
+// Note don't use docstring or else it ends up in help
+#[derive(Debug, StructOpt, Clone)]
+pub struct AccessLogOpt {
+ /// Path to folder where access log file will be generated
+ #[structopt(parse(from_os_str), required = true, short = "p", long = "path")]
+ path: PathBuf,
+
+ /// Data page size of the generated parquet file
+ #[structopt(long = "page-size")]
+ page_size: Option<usize>,
+
+ /// Data page size of the generated parquet file
+ #[structopt(long = "row-group-size")]
+ row_group_size: Option<usize>,
+
+ /// Total size of generated dataset. The default scale factor of 1.0 will generate a roughly 1GB parquet file
+ #[structopt(long = "scale-factor", default_value = "1.0")]
+ scale_factor: f32,
+}
+
+impl AccessLogOpt {
+ /// Create the access log and return the file.
+ ///
+ /// See [`TestParquetFile`] for more details
+ pub fn build(self) -> Result<TestParquetFile> {
+ let path = self.path.join("logs.parquet");
+
+ let mut props_builder = WriterProperties::builder();
+
+ if let Some(s) = self.page_size {
+ props_builder = props_builder
+ .set_data_page_size_limit(s)
+ .set_write_batch_size(s);
+ }
+
+ if let Some(s) = self.row_group_size {
+ props_builder = props_builder.set_max_row_group_size(s);
+ }
+ let props = props_builder.build();
+
+ let generator = AccessLogGenerator::new();
+
+ let num_batches = 100_f32 * self.scale_factor;
+
+ TestParquetFile::try_new(path, props, generator.take(num_batches as usize))
+ }
+}
diff --git a/benchmarks/src/util/mod.rs b/benchmarks/src/util/mod.rs
new file mode 100644
index 0000000000..95c6e5f53d
--- /dev/null
+++ b/benchmarks/src/util/mod.rs
@@ -0,0 +1,25 @@
+// 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.
+
+//! Shared benchmark utilities
+mod access_log;
+mod options;
+mod run;
+
+pub use access_log::AccessLogOpt;
+pub use options::CommonOpt;
+pub use run::{BenchQuery, BenchmarkRun};
diff --git a/benchmarks/src/options.rs b/benchmarks/src/util/options.rs
similarity index 85%
rename from benchmarks/src/options.rs
rename to benchmarks/src/util/options.rs
index d285741e23..1d86d10fb8 100644
--- a/benchmarks/src/options.rs
+++ b/benchmarks/src/util/options.rs
@@ -33,21 +33,22 @@ pub struct CommonOpt {
/// Batch size when reading CSV or Parquet files
#[structopt(short = "s", long = "batch-size", default_value = "8192")]
pub batch_size: usize,
+
+ /// Activate debug mode to see more details
+ #[structopt(short, long)]
+ pub debug: bool,
}
impl CommonOpt {
/// Return an appropriately configured `SessionConfig`
pub fn config(&self) -> SessionConfig {
- SessionConfig::new()
- .with_target_partitions(self.partitions)
- .with_batch_size(self.batch_size)
+ self.update_config(SessionConfig::new())
}
- pub fn iterations(&self) -> usize {
- self.iterations
- }
-
- pub fn partitions(&self) -> usize {
- self.partitions
+ /// Modify the existing config appropriately
+ pub fn update_config(&self, config: SessionConfig) -> SessionConfig {
+ config
+ .with_target_partitions(self.partitions)
+ .with_batch_size(self.batch_size)
}
}
diff --git a/benchmarks/src/run.rs b/benchmarks/src/util/run.rs
similarity index 100%
rename from benchmarks/src/run.rs
rename to benchmarks/src/util/run.rs