Skip to main content

bench_to_csv_null_num/
bench_to_csv_null_num.rs

1//! to_csv over a DataFrame with NULLABLE numeric and Bool columns + a string column.
2//! Before the nullable-Bool fast arm, that column forces the WHOLE frame onto the slow general
3//! writer. NEW builds every column typed (nullable numerics, nullable Bool, all-valid name) so
4//! the fast writer fires; CONTROL builds the name column eagerly (→ general writer) with
5//! identical data, isolating the whole-frame fast-vs-general delta the Bool arm unlocks.
6//!
7//! Run: cargo run -p fp-io --release --example bench_to_csv_null_num -- 1000000 6
8use std::collections::BTreeMap;
9
10use fp_columnar::{Column, ValidityMask};
11use fp_frame::DataFrame;
12use fp_index::Index;
13use fp_types::Scalar;
14
15fn main() {
16    let a: Vec<String> = std::env::args().collect();
17    let n: usize = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(1_000_000);
18    let iters: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(6);
19
20    let ids: Vec<i64> = (0..n as i64).collect();
21
22    // nullable Float64 "price": every 7th row missing.
23    let price: Vec<f64> = (0..n).map(|i| (i % 100000) as f64 / 100.0).collect();
24    let mut price_v = ValidityMask::all_valid(n);
25    // nullable Int64 "qty": every 5th row missing.
26    let qty: Vec<i64> = (0..n as i64).map(|i| i % 1000).collect();
27    let mut qty_v = ValidityMask::all_valid(n);
28    // nullable Bool "active": every 3rd row missing.
29    let active: Vec<bool> = (0..n).map(|i| i % 2 == 0).collect();
30    let mut active_v = ValidityMask::all_valid(n);
31    // all-valid string names (both frames share the same data).
32    let mut nb: Vec<u8> = Vec::with_capacity(n * 8);
33    let mut no: Vec<usize> = Vec::with_capacity(n + 1);
34    no.push(0);
35    let mut names_eager: Vec<Scalar> = Vec::with_capacity(n);
36    for i in 0..n {
37        if i % 7 == 0 {
38            price_v.set(i, false);
39        }
40        if i % 5 == 0 {
41            qty_v.set(i, false);
42        }
43        if i % 3 == 0 {
44            active_v.set(i, false);
45        }
46        let s = format!("item_{}", i % 5000);
47        nb.extend_from_slice(s.as_bytes());
48        no.push(nb.len());
49        names_eager.push(Scalar::Utf8(s));
50    }
51
52    let mk = |name_col: Column| -> DataFrame {
53        let mut cols: BTreeMap<String, Column> = BTreeMap::new();
54        cols.insert("id".to_string(), Column::from_i64_values_owned(ids.clone()));
55        cols.insert(
56            "price".to_string(),
57            Column::from_f64_values_with_validity(price.clone(), price_v.clone()),
58        );
59        cols.insert(
60            "qty".to_string(),
61            Column::from_i64_values_with_validity(qty.clone(), qty_v.clone()),
62        );
63        cols.insert(
64            "active".to_string(),
65            Column::from_bool_values_with_validity(active.clone(), active_v.clone()),
66        );
67        cols.insert("name".to_string(), name_col);
68        DataFrame::new(Index::new_known_unique_int64_unit_range(0, n), cols).unwrap()
69    };
70    let frame_fast = mk(Column::from_utf8_contiguous(nb.clone(), no.clone()));
71    let frame_general = mk(Column::from_values(names_eager).unwrap());
72
73    // The general frame's name column forces the whole frame off the fast path.
74    let ctl = frame_general.column("name").unwrap();
75    assert!(
76        ctl.as_utf8_contiguous().is_none() && ctl.as_nullable_utf8_contiguous().is_none(),
77        "control name column must force the general writer"
78    );
79
80    let mut best_t = u128::MAX;
81    for _ in 0..iters {
82        let t = std::time::Instant::now();
83        let s = fp_io::write_csv_string(&frame_fast).unwrap();
84        best_t = best_t.min(t.elapsed().as_nanos());
85        std::hint::black_box(s.len());
86    }
87    let mut best_c = u128::MAX;
88    for _ in 0..iters {
89        let t = std::time::Instant::now();
90        let s = fp_io::write_csv_string(&frame_general).unwrap();
91        best_c = best_c.min(t.elapsed().as_nanos());
92        std::hint::black_box(s.len());
93    }
94    let sf = fp_io::write_csv_string(&frame_fast).unwrap();
95    let sg = fp_io::write_csv_string(&frame_general).unwrap();
96    assert_eq!(sf, sg, "fast nullable CSV must byte-match the general writer");
97    println!(
98        "to_csv nullable-bool n={n} NEW(fast)={:>7.2}ms CONTROL(general)={:>7.2}ms speedup={:.3}x",
99        best_t as f64 / 1e6,
100        best_c as f64 / 1e6,
101        best_c as f64 / best_t as f64,
102    );
103}