Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-index/benches/indexes.rs

//! Index queries against the plain way of answering them. Synthetic address columns of
//! `KLEENE_BENCH_KEYS` keys (default 1M and 16M); the real set at `KLEENE_INDEX_SET`
//! when given (address columns, reach, why chains, sites, scopes). Times are the best of 5.

use std::collections::{HashMap, VecDeque};
use std::hint::black_box;
use std::time::Instant;

use arrow_array::cast::AsArray;
use kleene_gar::GarGraph;
use kleene_index::{AddrColumn, IndexSet, Kinds, Names, Store};
use kleene_sparse::CpuDevice;

struct Rng(u64);

impl Rng {
    fn next(&mut self) -> u64 {
        self.0 ^= self.0 >> 12;
        self.0 ^= self.0 << 25;
        self.0 ^= self.0 >> 27;
        self.0.wrapping_mul(0x2545_f491_4f6c_dd1d)
    }
}

/// Nanoseconds per item, best of 5 runs of `f` over `items` items.
fn ns(items: usize, mut f: impl FnMut() -> u64) -> f64 {
    let mut best = f64::MAX;
    for _ in 0..5 {
        let t = Instant::now();
        black_box(f());
        best = best.min(t.elapsed().as_secs_f64() * 1e9 / items as f64);
    }
    best
}

fn addresses(label: &str, keys: &[u64], qs: &[u64]) {
    let col = AddrColumn::build(keys.to_vec().into(), None).unwrap();
    let look = col.lookup().unwrap();
    let mut out = vec![None; qs.len()];
    let tree = ns(qs.len(), || {
        qs.iter()
            .map(|&q| u64::from(look.floor(q).unwrap_or(0)))
            .sum()
    });
    let batch = ns(qs.len(), || {
        look.floor_batch(qs, &mut out);
        out.iter().map(|o| u64::from(o.unwrap_or(0))).sum()
    });
    let binary = ns(qs.len(), || {
        qs.iter()
            .map(|&q| keys.partition_point(|&k| k <= q).saturating_sub(1) as u64)
            .sum()
    });
    let exact_q: Vec<u64> = qs
        .iter()
        .enumerate()
        .map(|(i, _)| keys[i * 7919 % keys.len()])
        .collect();
    let tree_exact = ns(exact_q.len(), || {
        exact_q
            .iter()
            .map(|&q| u64::from(look.exact(q).unwrap_or(0)))
            .sum()
    });
    let map: HashMap<u64, u32> = keys
        .iter()
        .enumerate()
        .map(|(i, &k)| (k, i as u32))
        .collect();
    let hash = ns(exact_q.len(), || {
        exact_q
            .iter()
            .map(|&q| u64::from(*map.get(&q).unwrap_or(&0)))
            .sum()
    });
    println!(
        "address {label:>14} {:>9} keys: floor tree {tree:6.1} ns, batch {batch:6.1} ns, binary search {binary:6.1} ns | exact tree {tree_exact:6.1} ns, hash map {hash:6.1} ns",
        keys.len()
    );
}

fn bfs_reaches(
    off: &[u64],
    adj: &[u32],
    a: u32,
    b: u32,
    seen: &mut [u32],
    mark: u32,
    q: &mut VecDeque<u32>,
) -> bool {
    q.clear();
    q.push_back(a);
    seen[a as usize] = mark;
    while let Some(v) = q.pop_front() {
        if v == b {
            return true;
        }
        for &w in &adj[off[v as usize] as usize..off[v as usize + 1] as usize] {
            if seen[w as usize] != mark {
                seen[w as usize] = mark;
                q.push_back(w);
            }
        }
    }
    false
}

fn real(dir: &str) {
    let kix = std::env::temp_dir().join(format!("kleene-bench-{}.kix", std::process::id()));
    let _ = std::fs::remove_dir_all(&kix);
    let t = Instant::now();
    let set = IndexSet::with(
        GarGraph::open(dir).unwrap(),
        Store::at(dir, &kix).unwrap(),
        CpuDevice::default(),
    );
    let rules = set.build_rules().unwrap();
    println!(
        "rule indexes built in {:.1} ms:",
        t.elapsed().as_secs_f64() * 1e3
    );
    for (name, d, _) in set.timings().entries {
        println!("  {name:44} {:8.3} ms", d.as_secs_f64() * 1e3);
    }
    let t = Instant::now();
    let again = IndexSet::with(
        GarGraph::open(dir).unwrap(),
        Store::at(dir, &kix).unwrap(),
        CpuDevice::default(),
    );
    let _ = again.build_rules().unwrap();
    println!(
        "read back from {} in {:.2} ms",
        kix.display(),
        t.elapsed().as_secs_f64() * 1e3
    );

    let mut r = Rng(3);
    let blk = set.column_u64("blk", "start").unwrap();
    let (lo, hi) = (blk[0], *blk.last().unwrap());
    let qs: Vec<u64> = (0..1 << 20).map(|_| lo + r.next() % (hi - lo)).collect();
    for (label, col) in [("func", "start"), ("blk", "start"), ("line", "addr")] {
        let keys = set.column_u64(label, col).unwrap();
        let mut k = keys.to_vec();
        k.dedup();
        addresses(&format!("{label}.{col}"), &k, &qs);
    }

    // reach: label query against a breadth-first search per pair
    let g = set.graph();
    for (edge, reach) in [
        ("inst_icall_inst", rules.inst_reach.as_ref()),
        ("func_fcall_func", rules.func_reach.as_ref()),
    ] {
        let Some(reach) = reach else { continue };
        let adj = g.adjacency(&g.edge_type(edge).unwrap().clone()).unwrap();
        let n = adj.sources as u64;
        let pairs: Vec<(u32, u32)> = (0..1 << 20)
            .map(|_| ((r.next() % n) as u32, (r.next() % n) as u32))
            .collect();
        let lab = ns(pairs.len(), || {
            pairs
                .iter()
                .map(|&(a, b)| u64::from(reach.reaches(a, b)))
                .sum()
        });
        let few = &pairs[..2000];
        let mut seen = vec![0u32; n as usize];
        let mut q = VecDeque::new();
        let mut mark = 0;
        let search = ns(few.len(), || {
            few.iter()
                .map(|&(a, b)| {
                    mark += 1;
                    u64::from(bfs_reaches(
                        &adj.out_offsets,
                        &adj.out_neighbours,
                        a,
                        b,
                        &mut seen,
                        mark,
                        &mut q,
                    ))
                })
                .sum()
        });
        let yes = pairs.iter().filter(|&&(a, b)| reach.reaches(a, b)).count();
        println!(
            "reach {edge:16} {n:>7} vertices, {} components, {} label entries: label {lab:6.1} ns, BFS {:9.1} ns per pair ({:.0}x); {:.1} % of pairs reach",
            reach.components(),
            reach.label_entries(),
            search,
            search / lab,
            100.0 * yes as f64 / pairs.len() as f64
        );
    }

    // who reaches a site: one bit against a search
    if let Some(sites) = rules.sites.as_ref() {
        let n = sites.vertices() as u64;
        let qs: Vec<(u32, usize)> = (0..1 << 20)
            .map(|_| {
                (
                    (r.next() % n) as u32,
                    (r.next() % sites.sets() as u64) as usize,
                )
            })
            .collect();
        let bit = ns(qs.len(), || {
            qs.iter()
                .map(|&(v, s)| u64::from(sites.reaches(v, s)))
                .sum()
        });
        println!(
            "sites: {} sets over {n} vertices: reaches-site query {bit:5.1} ns",
            sites.sets()
        );
    }

    // why chains: read back against a fresh search with parents
    if let Some(tree) = rules.why.first() {
        let n = tree.parents().len() as u32;
        let targets: Vec<u32> = (0..n).filter(|&v| tree.reached(v)).collect();
        let mut path = Vec::with_capacity(1024);
        let read = ns(targets.len(), || {
            targets
                .iter()
                .map(|&v| u64::from(tree.path_into(v, &mut path)) + path.len() as u64)
                .sum()
        });
        let adj = g
            .adjacency(&g.edge_type("inst_icall_inst").unwrap().clone())
            .unwrap();
        let few = &targets[..targets.len().min(500)];
        let mut seen = vec![0u32; n as usize];
        let mut q = VecDeque::new();
        let mut mark = 0;
        let search = ns(few.len(), || {
            few.iter()
                .map(|&v| {
                    mark += 1;
                    u64::from(bfs_reaches(
                        &adj.out_offsets,
                        &adj.out_neighbours,
                        tree.root(),
                        v,
                        &mut seen,
                        mark,
                        &mut q,
                    ))
                })
                .sum()
        });
        println!(
            "why chain from entry {}: {} reached, chain read {read:6.1} ns, BFS to the vertex {search:9.1} ns ({:.0}x)",
            tree.root(),
            targets.len(),
            search / read
        );
    }

    // scopes: inside (2 compares) against a parent walk; covering ranges against a scan
    if let (Some(nest), Some(ranges)) = (rules.scope_nest.as_ref(), rules.scope_ranges.as_ref()) {
        let parent = set.column_u32("scope", "parent").unwrap();
        let n = parent.len() as u64;
        let pairs: Vec<(u32, u32)> = (0..1 << 20)
            .map(|_| ((r.next() % n) as u32, (r.next() % n) as u32))
            .collect();
        let fast = ns(pairs.len(), || {
            pairs
                .iter()
                .map(|&(a, b)| u64::from(nest.inside(a, b)))
                .sum()
        });
        let walk = ns(pairs.len(), || {
            pairs
                .iter()
                .map(|&(a, b)| {
                    let mut x = a;
                    loop {
                        if x == b {
                            break 1;
                        }
                        if parent[x as usize] == u32::MAX {
                            break 0;
                        }
                        x = parent[x as usize];
                    }
                })
                .sum()
        });
        let rs = set.column_u64("scope_range", "start").unwrap();
        let re = set.column_u64("scope_range", "end").unwrap();
        let addrs = &qs[..1 << 16];
        let mut hits = Vec::with_capacity(64);
        let tree = ns(addrs.len(), || {
            addrs
                .iter()
                .map(|&a| {
                    hits.clear();
                    ranges.stab_into(a, &mut hits);
                    hits.len() as u64
                })
                .sum()
        });
        let few = &addrs[..1 << 10];
        let scan = ns(few.len(), || {
            few.iter()
                .map(|&a| (0..rs.len()).filter(|&k| rs[k] <= a && a < re[k]).count() as u64)
                .sum()
        });
        println!(
            "scopes: inside {fast:5.1} ns vs parent walk {walk:6.1} ns; covering ranges {tree:6.1} ns vs scan {scan:9.1} ns ({} ranges)",
            rs.len()
        );
    }
    let _ = std::fs::remove_dir_all(&kix);
}

/// Name to id: the perfect hash (with its string check) against a hash map of strings
/// and a binary search over the sorted names; build times too.
fn names(n: usize, r: &mut Rng) {
    let words = ["parse", "lex", "eval", "core", "fmt", "drop", "iter", "map"];
    let v: Vec<String> = (0..n)
        .map(|i| {
            format!(
                "{}::{}::{}_{i}",
                words[(r.next() % 8) as usize],
                words[(r.next() % 8) as usize],
                words[(r.next() % 8) as usize]
            )
        })
        .collect();
    let col: arrow_array::ArrayRef = std::sync::Arc::new(arrow_array::StringArray::from(v.clone()));
    let t = Instant::now();
    let ix = Names::build(&col).unwrap();
    let build = t.elapsed().as_secs_f64() * 1e3;
    let qs: Vec<&str> = (0..1 << 20)
        .map(|_| v[(r.next() % n as u64) as usize].as_str())
        .collect();
    let mph = ns(qs.len(), || {
        qs.iter().map(|q| u64::from(ix.id(q).unwrap_or(0))).sum()
    });
    // the slot alone: the hash, the pilot, the remap (no slot read, no compare)
    let place = ns(qs.len(), || qs.iter().map(|q| ix.hash_of(q) as u64).sum());
    // the map built the same way: keys are the column's own bytes, not the queries'
    let strs = col.as_string::<i32>();
    let t = Instant::now();
    let map: HashMap<&str, u32> = (0..n).map(|i| (strs.value(i), i as u32)).collect();
    let map_build = t.elapsed().as_secs_f64() * 1e3;
    let hash = ns(qs.len(), || {
        qs.iter()
            .map(|q| u64::from(*map.get(q).unwrap_or(&0)))
            .sum()
    });
    let mut sorted: Vec<(&str, u32)> = map.iter().map(|(&s, &i)| (s, i)).collect();
    sorted.sort_unstable();
    let binary = ns(qs.len(), || {
        qs.iter()
            .map(|q| {
                let k = sorted.partition_point(|x| x.0 < *q);
                u64::from(sorted[k].1)
            })
            .sum()
    });
    let missing: Vec<String> = (0..1 << 16).map(|i| format!("absent::{i}")).collect();
    let miss = ns(missing.len(), || {
        missing.iter().map(|q| u64::from(ix.id(q).is_some())).sum()
    });
    println!(
        "names {n:>9}: perfect hash {mph:6.1} ns (slot alone {place:5.1} ns, miss {miss:5.1} ns, build {build:7.1} ms), hash map over the column {hash:6.1} ns (build {map_build:7.1} ms), binary search {binary:6.1} ns"
    );
}

/// "Is v a K" and "the vertices of K": the kind bitmaps against a scan of the kind column.
fn kinds(n: usize, r: &mut Rng) {
    let kind: Vec<u64> = (0..n).map(|_| r.next() % 24).collect();
    let t = Instant::now();
    let k = Kinds::build(&kind, 1 << 30).unwrap();
    let build = t.elapsed().as_secs_f64() * 1e3;
    let qs: Vec<(u64, u32)> = (0..1 << 20)
        .map(|_| (r.next() % 24, (r.next() % n as u64) as u32))
        .collect();
    let has = ns(qs.len(), || {
        qs.iter().map(|&(x, v)| u64::from(k.has(x, v))).sum()
    });
    let col = ns(qs.len(), || {
        qs.iter()
            .map(|&(x, v)| u64::from(kind[v as usize] == x))
            .sum()
    });
    let list = ns(n, || k.ids(5).map(u64::from).sum());
    let scan = ns(n, || {
        kind.iter()
            .enumerate()
            .filter(|&(_, &x)| x == 5)
            .map(|(v, _)| v as u64)
            .sum()
    });
    println!(
        "kinds {n:>9} (24 kinds): has {has:5.2} ns vs column {col:5.2} ns | ids of one kind {list:5.2} ns/vertex vs scan {scan:5.2} ns/vertex | build {build:7.1} ms"
    );
}

fn main() {
    let sizes: Vec<usize> = std::env::var("KLEENE_BENCH_KEYS")
        .ok()
        .map(|s| s.split(',').filter_map(|x| x.parse().ok()).collect())
        .unwrap_or_else(|| vec![1 << 20, 1 << 24]);
    let mut r = Rng(1);
    for n in sizes {
        // rising addresses about 64 bytes apart, inside 4 GiB
        let mut keys: Vec<u64> = (0..n)
            .map(|_| 0x40_0000 + r.next() % (n as u64 * 64))
            .collect();
        keys.sort_unstable();
        keys.dedup();
        let span = keys.last().unwrap() - keys[0];
        let qs: Vec<u64> = (0..1 << 22).map(|_| keys[0] + r.next() % span).collect();
        addresses("synthetic", &keys, &qs);
        names(n, &mut r);
        kinds(n, &mut r);
    }
    if let Ok(dir) = std::env::var("KLEENE_INDEX_SET") {
        real(&dir);
    }
}