Skip to main content

bench_to_csv/
bench_to_csv.rs

1//! Bench + golden for write_csv_string — hoist per-cell column lookup.
2//!
3//! Run: cargo run -p fp-io --example bench_to_csv --release
4//!
5//! The row loop did a `frame.column(name)` BTreeMap-by-name lookup per CELL
6//! (O(N·C·log C)); resolving the column refs once before the loop makes it
7//! O(N·C). Output is byte-identical.
8
9use std::{collections::BTreeMap, time::Instant};
10
11use fp_columnar::Column;
12use fp_frame::DataFrame;
13use fp_index::{Index, IndexLabel};
14use fp_io::write_csv_string;
15use fp_types::{NullKind, Scalar};
16
17fn frame(n_rows: usize, n_cols: usize, salt: i64) -> DataFrame {
18    let labels: Vec<IndexLabel> = (0..n_rows as i64).map(IndexLabel::Int64).collect();
19    let mut order = Vec::new();
20    let mut cols = BTreeMap::new();
21    for c in 0..n_cols {
22        let name = format!("col{c:03}");
23        let vals: Vec<Scalar> = (0..n_rows as i64)
24            .map(|i| {
25                if (i + c as i64) % 17 == 0 {
26                    Scalar::Null(NullKind::NaN)
27                } else if c % 2 == 0 {
28                    Scalar::Int64(i.wrapping_mul(salt + c as i64).wrapping_add(1))
29                } else {
30                    Scalar::Float64((i as f64) * 0.5 - (c as f64))
31                }
32            })
33            .collect();
34        cols.insert(name.clone(), Column::from_values(vals).unwrap());
35        order.push(name);
36    }
37    DataFrame::new_with_column_order(Index::new(labels), cols, order).unwrap()
38}
39
40fn golden() -> String {
41    // Small mixed frame incl nulls, ints, floats, strings.
42    let labels: Vec<IndexLabel> = (0..4i64).map(IndexLabel::Int64).collect();
43    let mut cols = BTreeMap::new();
44    cols.insert(
45        "a".to_string(),
46        Column::from_values(vec![
47            Scalar::Int64(1),
48            Scalar::Null(NullKind::NaN),
49            Scalar::Int64(-3),
50            Scalar::Int64(42),
51        ])
52        .unwrap(),
53    );
54    cols.insert(
55        "b".to_string(),
56        Column::from_values(vec![
57            Scalar::Float64(1.5),
58            Scalar::Float64(-0.0),
59            Scalar::Float64(2.25),
60            Scalar::Null(NullKind::NaN),
61        ])
62        .unwrap(),
63    );
64    cols.insert(
65        "c".to_string(),
66        Column::from_values(
67            ["x", "y,z", "", "q\"q"]
68                .iter()
69                .map(|s| Scalar::Utf8((*s).to_string()))
70                .collect(),
71        )
72        .unwrap(),
73    );
74    let df = DataFrame::new_with_column_order(
75        Index::new(labels),
76        cols,
77        vec!["a".into(), "b".into(), "c".into()],
78    )
79    .unwrap();
80    write_csv_string(&df).unwrap()
81}
82
83fn main() {
84    let g = golden();
85    print!("GOLDEN_BEGIN\n{g}GOLDEN_END\n");
86
87    // Wide frame: many columns => the per-cell BTreeMap lookup dominates.
88    let df = frame(40_000, 60, 7);
89
90    let _ = write_csv_string(&df).unwrap(); // warmup
91
92    let t = Instant::now();
93    let s = write_csv_string(&df).unwrap();
94    let d = t.elapsed();
95    std::hint::black_box(s.len());
96
97    println!(
98        "TIMING rows=40000 cols=60 to_csv={:.3}ms",
99        d.as_secs_f64() * 1e3
100    );
101}