Skip to main content

bench_to_csv_null_utf8/
bench_to_csv_null_utf8.rs

1//! to_csv over a DataFrame with all-valid numeric columns + a NULLABLE Utf8 column.
2//! Before the FastCol::UN arm, one null-bearing string column forced the WHOLE frame onto
3//! the slow general (Scalar + csv-record) writer. NEW builds the nullable Utf8 column as a
4//! LazyNullableUtf8 backing (→ fast typed writer); CONTROL builds it eagerly (→ general
5//! writer) so the two are byte-identical but exercise different writers.
6//!
7//! Run: cargo run -p fp-io --release --example bench_to_csv_null_utf8 -- 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    // all-valid numeric columns
21    let ids: Vec<i64> = (0..n as i64).collect();
22    let vals: Vec<f64> = (0..n).map(|i| (i % 100000) as f64 / 100.0).collect();
23
24    // nullable Utf8 "name": every 5th row missing, else item_{c}.
25    let mut bytes: Vec<u8> = Vec::with_capacity(n * 10);
26    let mut offsets: Vec<usize> = Vec::with_capacity(n + 1);
27    offsets.push(0);
28    let mut validity = ValidityMask::all_valid(n);
29    let mut eager: Vec<Scalar> = Vec::with_capacity(n);
30    for i in 0..n {
31        if i % 5 == 0 {
32            validity.set(i, false);
33            eager.push(Scalar::Null(fp_types::NullKind::Null));
34        } else {
35            let s = format!("item_{}", i % 5000);
36            bytes.extend_from_slice(s.as_bytes());
37            eager.push(Scalar::Utf8(s));
38        }
39        offsets.push(bytes.len());
40    }
41
42    let mk = |name_col: Column| -> DataFrame {
43        let mut cols: BTreeMap<String, Column> = BTreeMap::new();
44        cols.insert("id".to_string(), Column::from_i64_values_owned(ids.clone()));
45        cols.insert("value".to_string(), Column::from_f64_values(vals.clone()));
46        cols.insert("name".to_string(), name_col);
47        DataFrame::new(Index::new_known_unique_int64_unit_range(0, n), cols).unwrap()
48    };
49
50    let frame_fast = mk(Column::from_utf8_values_with_validity(
51        bytes.clone(),
52        offsets.clone(),
53        validity,
54    ));
55    let frame_general = mk(Column::from_values(eager).unwrap());
56
57    // Confirm the control's name column is off the fast path (general writer).
58    let ctl_name = frame_general.column("name").unwrap();
59    assert!(
60        ctl_name.as_utf8_contiguous().is_none() && ctl_name.as_nullable_utf8_contiguous().is_none(),
61        "control name column must NOT be on the fast Utf8 path"
62    );
63
64    let mut best_t = u128::MAX;
65    for _ in 0..iters {
66        let t = std::time::Instant::now();
67        let s = fp_io::write_csv_string(&frame_fast).unwrap();
68        best_t = best_t.min(t.elapsed().as_nanos());
69        std::hint::black_box(s.len());
70    }
71    let mut best_c = u128::MAX;
72    for _ in 0..iters {
73        let t = std::time::Instant::now();
74        let s = fp_io::write_csv_string(&frame_general).unwrap();
75        best_c = best_c.min(t.elapsed().as_nanos());
76        std::hint::black_box(s.len());
77    }
78    // Byte-for-byte parity.
79    let sf = fp_io::write_csv_string(&frame_fast).unwrap();
80    let sg = fp_io::write_csv_string(&frame_general).unwrap();
81    assert_eq!(sf, sg, "fast (nullable-Utf8) CSV must byte-match the general writer");
82    println!(
83        "to_csv nullable-utf8 n={n} NEW(fast)={:>7.2}ms CONTROL(general)={:>7.2}ms speedup={:.3}x",
84        best_t as f64 / 1e6,
85        best_c as f64 / 1e6,
86        best_c as f64 / best_t as f64,
87    );
88}