Skip to main content

bench_to_json_str/
bench_to_json_str.rs

1//! to_json(records) over a frame with a Utf8 column. bench_to_json_str <n>
2use std::collections::BTreeMap;
3
4use fp_columnar::Column;
5use fp_frame::DataFrame;
6use fp_index::Index;
7use fp_io::JsonOrient;
8
9fn main() {
10    let a: Vec<String> = std::env::args().collect();
11    let n: usize = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(1_000_000);
12    let ints: Vec<i64> = (0..n as i64)
13        .map(|i| (i.wrapping_mul(2_654_435_761)) % 1_000_000)
14        .collect();
15    // Contiguous Utf8 backing (what read_csv / string ops produce).
16    let mut sbytes: Vec<u8> = Vec::new();
17    let mut soff: Vec<usize> = vec![0];
18    for i in 0..n {
19        sbytes.extend_from_slice(format!("item_{}", i % 1000).as_bytes());
20        soff.push(sbytes.len());
21    }
22    let mut cols: BTreeMap<String, Column> = BTreeMap::new();
23    cols.insert("a".to_string(), Column::from_i64_values(ints));
24    cols.insert("s".to_string(), Column::from_utf8_contiguous(sbytes, soff));
25    let frame = DataFrame::new(Index::new_known_unique_int64_unit_range(0, n), cols).unwrap();
26    let mut best = u128::MAX;
27    for _ in 0..6 {
28        let t = std::time::Instant::now();
29        let s = fp_io::write_json_string(&frame, JsonOrient::Records).unwrap();
30        std::hint::black_box(s.len());
31        let e = t.elapsed().as_nanos();
32        if e < best {
33            best = e;
34        }
35    }
36    println!(
37        "to_json(records) +str n={n}: best={best}ns ({:.2}ms)",
38        best as f64 / 1e6
39    );
40}