Apache DataFusion SQL Query Engine
ARROW-9919: [Rust][DataFusion] Speedup math operations by 15%+
Jorge C. Leitaob09012336343
diff --git a/rust/datafusion/Cargo.toml b/rust/datafusion/Cargo.tomlindex 4d7ca3f415..c5c7900a63 100644--- a/rust/datafusion/Cargo.toml+++ b/rust/datafusion/Cargo.toml@@ -70,3 +70,7 @@ harness = false[[bench]]name = "sort_limit_query_sql"harness = false++[[bench]]+name = "math_query_sql"+harness = falsediff --git a/rust/datafusion/benches/math_query_sql.rs b/rust/datafusion/benches/math_query_sql.rsnew file mode 100644index 0000000000..151a28e547--- /dev/null+++ b/rust/datafusion/benches/math_query_sql.rs@@ -0,0 +1,100 @@+// 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.++#[macro_use]+extern crate criterion;+use criterion::Criterion;++use std::sync::Arc;++extern crate arrow;+extern crate datafusion;++use arrow::{+ array::{Float32Array, Float64Array},+ datatypes::{DataType, Field, Schema},+ record_batch::RecordBatch,+};+use datafusion::error::Result;++use datafusion::datasource::MemTable;+use datafusion::execution::context::ExecutionContext;++fn query(ctx: &mut ExecutionContext, sql: &str) {+ // execute the query+ let df = ctx.sql(&sql).unwrap();+ let results = df.collect().unwrap();++ // display the relation+ for _batch in results {}+}++fn create_context(array_len: usize, batch_size: usize) -> Result<ExecutionContext> {+ // define a schema.+ let schema = Arc::new(Schema::new(vec![+ Field::new("f32", DataType::Float32, false),+ Field::new("f64", DataType::Float64, false),+ ]));++ // define data.+ let batches = (0..array_len / batch_size)+ .map(|i| {+ RecordBatch::try_new(+ schema.clone(),+ vec![+ Arc::new(Float32Array::from(vec![i as f32; batch_size])),+ Arc::new(Float64Array::from(vec![i as f64; batch_size])),+ ],+ )+ .unwrap()+ })+ .collect::<Vec<_>>();++ let mut ctx = ExecutionContext::new();++ // declare a table in memory. In spark API, this corresponds to createDataFrame(...).+ let provider = MemTable::new(schema, vec![batches])?;+ ctx.register_table("t", Box::new(provider));++ Ok(ctx)+}++fn criterion_benchmark(c: &mut Criterion) {+ c.bench_function("sqrt_20_12", |b| {+ let array_len = 1048576; // 2^20+ let batch_size = 4096; // 2^12+ let mut ctx = create_context(array_len, batch_size).unwrap();+ b.iter(|| query(&mut ctx, "SELECT sqrt(f32) FROM t"))+ });++ c.bench_function("sqrt_22_12", |b| {+ let array_len = 4194304; // 2^22+ let batch_size = 4096; // 2^12+ let mut ctx = create_context(array_len, batch_size).unwrap();+ b.iter(|| query(&mut ctx, "SELECT sqrt(f32) FROM t"))+ });++ c.bench_function("sqrt_22_14", |b| {+ let array_len = 4194304; // 2^22+ let batch_size = 16384; // 2^14+ let mut ctx = create_context(array_len, batch_size).unwrap();+ b.iter(|| query(&mut ctx, "SELECT sqrt(f32) FROM t"))+ });+}++criterion_group!(benches, criterion_benchmark);+criterion_main!(benches);diff --git a/rust/datafusion/src/physical_plan/math_expressions.rs b/rust/datafusion/src/physical_plan/math_expressions.rsindex aad1958d5c..8647699481 100644--- a/rust/datafusion/src/physical_plan/math_expressions.rs+++ b/rust/datafusion/src/physical_plan/math_expressions.rs@@ -17,25 +17,30 @@//! Math expressions-use crate::error::{ExecutionError, Result};--use arrow::array::{Array, ArrayRef, Float32Array, Float64Array, Float64Builder};+use std::sync::Arc;-use arrow::datatypes::DataType;+use arrow::array::{make_array, Array, ArrayData, ArrayRef, Float32Array, Float64Array};+use arrow::buffer::Buffer;+use arrow::datatypes::{DataType, ToByteSlice};-use std::sync::Arc;+use crate::error::{ExecutionError, Result};macro_rules! compute_op {($ARRAY:expr, $FUNC:ident, $TYPE:ident) => {{- let mut builder = Float64Builder::new($ARRAY.len());- for i in 0..$ARRAY.len() {- if $ARRAY.is_null(i) {- builder.append_null()?;- } else {- builder.append_value($ARRAY.value(i).$FUNC() as f64)?;- }- }- Ok(Arc::new(builder.finish()))+ let len = $ARRAY.len();+ let result = (0..len)+ .map(|i| $ARRAY.value(i).$FUNC() as f64)+ .collect::<Vec<f64>>();+ let data = ArrayData::new(+ DataType::Float64,+ len,+ Some($ARRAY.null_count()),+ $ARRAY.data().null_buffer().cloned(),+ 0,+ vec![Buffer::from(result.to_byte_slice())],+ vec![],+ );+ Ok(make_array(Arc::new(data)))}};}